在微信小程序中经验遇到对文件进行预览,或者转发、借助第三方应用打开的功能实现。需要借助wx.openDocument进行实现
1、定义html,点击之后进行预览
<view @click="view('文件网络地址')">
《文件标题》
</view>
2、view实现,如果没有对不同手机系统的特殊要求,可以跳过view方法,直接执行openReport方法。
由于wx.openDocument需要一个本地地址,所以先借助wx.downloadFile生成一个tempFilePath临时本地路径。
view(index) {
let pdfUrl = this.pdfUrlList[index];
switch (uni.getSystemInfoSync().platform) {
case 'android':
console.log('安卓');
// 这里直接调用原生的方法
this.openReport(pdfUrl);
break;
case 'ios':
console.log('IOS');
this.openReport(pdfUrl);
//这里跳转web-view页面
// uni.navigateTo({
// url: `/pages/mine/my-report/detail?reportFileUrl=${item.reportFileUrl}`
// });
break;
default:
this.openReport(pdfUrl);
break;
}
},
openReport(url) {
uni.showLoading({
title: '加载中',
mask: true,
});
wx.downloadFile({
url: url,
success: function (res) {
uni.hideLoading();
var filePath = res.tempFilePath;
uni.showLoading({
title: '正在打开',
mask: true,
});
wx.openDocument({
filePath: filePath,
fileType: 'pdf',
showMenu: true,
success: function (res) {
uni.hideLoading();
console.log('打开文档成功');
},
fail: function (err) {
uni.hideLoading();
console.log('fail:' + JSON.stringify(err));
},
});
},
fail: function (err) {
uni.hideLoading();
console.log('fail:' + JSON.stringify(err));
},
});
},
实现效果如下:点击右上角三点可实现其他方式打开