說明 word/excel/ppt/pdf是從用戶端會話選擇檔案。使用chooseMessageFile中選擇檔案。
一、wxml檔案
上傳按鈕,綁定chooseFile
<!--上傳檔案(word/excel/ppt/pdf等)到雲存儲-->
<button bindtap="chooseFile" type="primary" >上傳檔案</button>
二、wxss檔案
wxss設定按鈕外邊距
button{
margin: 30rpx;
}
三、js檔案
實作檔案選擇和檔案上傳的功能
Page({
//功能:上傳檔案(word/excel/ppt/pdf等)到雲存儲
//第一步:選擇檔案
chooseFile(){
let that = this
wx.chooseMessageFile({
count: 1,
type: 'all',
success (res) {
// tempFilePath可以作為img标簽的src屬性顯示圖檔
const tempFilePaths = res.tempFiles
let tempFile = tempFilePaths[0]
that.uploadFile(tempFile.name,tempFile.path)
}
})
},
//第二步:通過uploadFile上傳選中的檔案
uploadFile(fileName,tempFile){
wx.cloud.uploadFile({
cloudPath:fileName,
filePath:tempFile,
})
.then(res=>{
console.log("上傳成功啦",res);
wx.showToast({
title: '檔案上傳成功',
icon:"success",
duration:2000
})
})
.catch(err=>{
console.log("上傳失敗啦",err);
})
}
})
四、效果展示
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIml2ZuQDM3gjNzkDM30SN3ATNzAjM1ETOxcDMxIDMy0yN4MjN5MjMvw1NwEjMwIzLcdDOzYTOzIzLcd2bsJ2Lc12bj5ycn9Gbi52YuAjMwIzZtl2Lc9CX6MHc0RHaiojIsJye.gif)