小程序 H5 PDF预览(wx.openDocument)

文章描述了在H5页面嵌入到微信小程序时遇到的问题,即H5中的预览和下载功能在小程序环境中无法正常工作。作者提供了一个解决方案,通过在入口文件中检测环境,然后针对小程序环境使用wx.miniProgram.navigateTo跳转至特定页面,并在小程序页面中处理请求,下载文件并使用wx.openDocument打开PDF文件。
摘要由CSDN通过智能技术生成

H5嵌入小程序时,h5中使用预览、下载是正常的。唯独小程序中是不可以的。

话不多说上干货:

1、首先要在入口文件中判断当前环境是什么

const { userAgent } = window.navigator;
const ismini = /miniProgram/i.test(userAgent);		//微信小程序
if(ismini){
	const url = encodeURIComponent(`${window.location.origin}/epolicy/getDocument?        businessType=1&policyType=${policyType}&tradeTime=${tradeTime}&businessCode=${this.policyNo}`)
	window.wx.miniProgram.navigateTo({
		url: `/pages/load/onload/index?url=${url}`,
		
	});
}else{
	window.open(`${window.location.origin}/epolicy/getDocument?businessType=1&policyType=${policyType}&tradeTime=${tradeTime}&businessCode=${this.policyNo}`)
				}

2、在小程序的承接页面中/pages/load/onload/index加入代码

var config = require('../../../utils/config.js');
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		newsrc: true,
		name: '',
		code: '',
	},
	/**
	 * 监听页面加载
	 */
	onLoad: function(options) {
		var arr = decodeURIComponent(options.url).split("&");
		var obj = {};
		for (var i = 0; i < arr.length; i++) {
			var g = arr[i].split("=");
			obj[g[0]] = g[1];
		}
		if (obj.policyNo) {
			this.setData({
				name: '电子发票',
				code: obj.policyNo
			})
		}
		let newurl = decodeURIComponent(options.url)
		wx.request({
			url: newurl,
			header: {
				"content-type": "application/json",
			},
			responseType: "arraybuffer", //注意这里的responseType
			success: (result) => {
				var fileManager = wx.getFileSystemManager();
				var FilePath = wx.env.USER_DATA_PATH + "/" + `${this.data.code}_invoice.pdf`;
				fileManager.writeFile({
					data: result.data,
					filePath: FilePath,
					encoding: "binary", //编码方式 
					success: res => {
						this.setData({
							newsrc: false
						})
						wx.openDocument({ //我这里成功之后直接打开
							filePath: FilePath,
							showMenu: true,
							fileType: "pdf",
							success: result => {
								console.log("打开文档成功");
							},
							fail: err => {
								console.log("打开文档失败", err);
							}
						});
					},
					fail: res => {
						wx.showToast({
							title: '导出失败!',
							icon: 'none', //默认值是success,就算没有icon这个值,就算有其他值最终也显示success
							duration: 2000, //停留时间
						})
						console.log(res);
					}
				})
			},
			fail(err) {
				console.log(err)
			}
		})
	},

	/**
	 * 监听页面初次渲染完成
	 */
	onReady: function() {


	},

	/**
	 * 监听页面显示
	 */
	onShow: function() {

		if (this.data.newsrc == false) {
			this.setData({
				newsrc: true
			})
		}
	},

	/**
	 * 监听页面隐藏
	 */
	onHide: function() {

		if (this.data.newsrc == false) {
			this.setData({
				newsrc: true
			})
		}
	},

	/**
	 * 监听页面卸载
	 */
	onUnload: function() {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {}
})

⼩程序下载⽂件并预览 需求分析 最近优化了个原先写过的需求,回头复习复习⼩程序的 API 是这样的,我需要下载⼀个⽂件并打开此⽂件 优化:记录是否被下载过,如果下载过就直接打开 获取⽂件下载链接,打开⽂件 wx.downloadFile({ url: `${pic.meetingUrl}/weixin/noticeStart/downLoad/${this.selectItem.recordId}`, // 下载资源的 url success: (res) => { wx.openDocument({ filePath: res.tempFilePath, // ⽂件路径,可通过 downloadFile 获得, fileType: 'pdf', // 写下载后的⽂件的格式,这⾥距离是pdf success: (res) => { }, fail: (error) => { }, }); }, fail: () => {}, complete: () => {}, }); 优化 思路:保存下载后的⽂件,保存其路径到本地缓存,然后下次打开的时候判断⼀下本地缓存⾥是否有,如果有就打开,本地缓存没有的话, 就先下载在打开。 const that = this; const cacheFilePath = wx.getStorageSync( `filePath-${this.selectItem.recordId}` ); // 先判断这个⽂件是否下载过 // 如果下载过,尝试通过缓存,打开⽂件 // 否则就要下载,下载成功后保存本地缓存(临时路径信息),命名规则为 filePath + recordId if (cacheFilePath) { wx.openDocument({ filePath: cacheFilePath, //⽂件路径,可通过 downFile 获得, fileType: this.selectItem.fileType, // 获取⽂件格式 success: (res) => { }, fail: (error) => { }, }); } else { wx.showLoading({ title: "下载中", mask: true, }); wx.downloadFile({ url: `${pic.meetingUrl}/weixin/noticeStart/downLoad/${this.selectItem.recordId}`, // 下载资源的 url success: (res) => { // 隐藏 loading wx.hideLoading(); // 下载成功后,保存⽂件路径到本地缓存 wx.setStorageSync( `filePath-${this.selectItem.recordId}`, `${res.tempFilePath}` ); // 尝试打开下载后的⽂件 wx.openDocument({ filePath: res.tempFilePath, //⽂件路径,可通过 downFile 获得, fileType: this.selectItem.fileType, // 获取⽂件格式 success: (res) => { }, fail: (error) => { }, }); }, fail: () => {}, complete: () => {}, }); }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值