上传word和pdf等文件到云存储
1.设置按钮和点击事件
<button bindtap="chooseFile">选择文件</button>
2.第一步选择文件
javascript"> //上传文件第一步:选择文件
chooseFile() {
wx.chooseMessageFile({
count: 1,
type: 'all',
}).then(res=>{
console.log(res)
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFiles
let temFile=res.tempFiles[0]
this.uploadFile(temFile.name,temFile.path)
}).catch(err=>{
console.error("选择文件失败",err)
})
}
3.第二步,上传至云存储
javascript"> //上传文件第二步,通过uploadFile上传选中的文件
uploadFile(name,tempUrl) {
wx.cloud.uploadFile({
cloudPath:name,
filePath:tempUrl
}).then(res=>{
console.log("上传文件成功",res)
}).catch(err=>{
console.error("上传文件失败",err)
})
4.可成功上传word、pdf、excel文件
下载文件
1.编辑输入框和下载点击按钮
请输入下载链接
<input bindinput="getContent"></input>
<button bindtap="downloadFile">点击下载</button>
2.获取输入框中的用户下载链接,并设置全局变量fileID
javascript"> //获取用户输入的下载链接
getContent(e) {
this.setData({
fileID: e.detail.value
})
}
3.下载文件代码
javascript"> //下载文件
downloadFile() {
let downloadfileID = this.data.fileID
console.log('下载链接', downloadfileID)
if (downloadfileID != null && downloadfileID.length > 0) {
wx.cloud.downloadFile({
fileID: downloadfileID
}).then(res => {
console.log('下载成功', res)
}).catch(err => {
console.error('下载失败', err)
})
} else {
wx.showToast({
icon: "none",
title: '下载链接为空了',
})
}
}
4.下载成功
打开并查看下载好的文件
将打开的代码添加到下载文件成功的方法中
javascript">wx.openDocument({
filePath: res.tempFilePath,
success: function (res) {
console.log('打开文档成功')
}
})
可以在word中打开
改进从电脑中选择文件后直接打开
javascript">//上传文件第二步,通过uploadFile上传选中的文件
uploadFile(name, tempUrl) {
wx.cloud.uploadFile({//上传文件
cloudPath: name,
filePath: tempUrl
}).then(res => {
console.log("上传文件成功", res)
wx.cloud.downloadFile({//上传成功后下载文件
fileID: res.fileID
}).then(res => {
console.log('下载成功', res)
wx.openDocument({//下载成功以后打开文件
filePath: res.tempFilePath,
success: function (res) {
console.log('打开文档成功')
}
})
}).catch(err => {
console.error('下载失败', err)
})
}).catch(err => {
console.error("上传文件失败", err)
})
}
改进后打开的pdf文件
手机真机调试
选择聊天记录里的任意一个文件,这里选择的是一个pdf
选择成功后自动打开
调试内容显示
复制链接后打开效果