代码
<button @click="viewFile">查看文件</button>
<button @click="shareFile">分享给好友</button>
//查看文件
viewFile(){
const _this = this
//如果该文件已经下载可以直接打开
if(this.filePath){
uni.openDocument({
filePath: _this.filePath,
showMenu: true,
success: function (res) {
console.log('打开文档成功');
}
});
}else{
//否则首先调用下载方法
uni.downloadFile({
//此处url为需要分享的文件的url
url: 文件url,
success: function (res) {
_this.filePath = res.tempFilePath;
uni.openDocument({
filePath: _this.filePath,
showMenu: true,
success: function (res) {
console.log('打开文档成功');
}
});
}
});
}
},
shareFile(){
const _this = this
//如果该文件已经下载可以直接分享
if(this.filePath){
wx.shareFileMessage({
filePath: _this.filePath,
success() {},
fail: console.error,
})
}else{
//否则首先调用下载方法
uni.downloadFile({
//此处url为需要分享的文件的url
url: 文件url,
success: function (res) {
_this.filePath = res.tempFilePath;
wx.shareFileMessage({
filePath: _this.filePath,
success() {},
fail: console.error,
})
}
});
}
}
官网
下载方法(uniapp)
uni.uploadFile(OBJECT) | uni-app官网
新页面打开文档(uniapp)
uni.saveFile(OBJECT) @savefile | uni-app官网
转发(微信小程序)
wx.shareFileMessage(Object object) | 微信开放文档
注意
-
转发分享仅在微信小程序中生效
-
查看文件,类型仅支持doc, xls, ppt, pdf, docx, xlsx, pptx