话不多说,直接上代码:
wxml页面:
<view bindtap="chooseFile">上传</view>
js页面:
//第一步:选择文件
chooseFile(){
let that = this
wx.chooseMessageFile({
count: 1,
type: 'all', // all 代表所有类型的文件都可以上传
success (res) {
wx.showLoading({
title: '上传中...',
});
// 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.hideLoading()
wx.showToast({
title: '文件上传成功',
icon:"success",
duration:2000
})
})
.catch(err=>{
console.log("上传失败啦",err);
})
}