一、wxml文件
<!-- 上傳、下載、打開文件一步執行 --> <view class="handle"> <button bindtap="handleFile" type="primary">上傳下載打開文件</button> <text>實現文件的上傳、下載、打開一步到位</text> </view>
二、wxss文件
.handle{ margin: 200rpx 20rpx 0 20rpx; text-align: center; }
三、js文件
Page({ data:{ fileID :null }, //功能:上傳、下載、打開文件一氣呵成 handleFile(){ //選擇文件 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(fileName,tempFile){ wx.cloud.uploadFile({ cloudPath:fileName, filePath:tempFile, }) .then(res=>{ console.log("文件上傳成功",res); //下載文件 wx.cloud.downloadFile({ fileID: res.fileID, success: res => { console.log("文件下載成功",res); //打開文件 const filePath = res.tempFilePath wx.openDocument({ filePath: filePath, success: function (res) { console.log('文件打開成功',res) } }) } }) }) .catch(err=>{ console.log("文件上傳失敗",err); }) } })
四、實現效果