Use wx.openDocument(Object object) to realize the uniaapp applet to open files for preview

In the WeChat applet, I encountered the function of previewing files, or forwarding them, and opening them with the help of third-party applications. It needs to be implemented with wx.openDocument

1. Define html, click to preview

<view @click="view('文件网络地址')">
   《文件标题》
</view>

2. View implementation. If there are no special requirements for different mobile phone systems, you can skip the view method and directly execute the openReport method.
Since wx.openDocument needs a local address, first use wx.downloadFile to generate a tempFilePath temporary local path.

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));
		},
	});
},

The effect is as follows: Click the three dots in the upper right corner to open in other ways
insert image description here

Guess you like

Origin blog.csdn.net/qq_42563079/article/details/130280998