解决方案大体就两种
- 方案一简单有效
如果微信api下载失败有很大可能是第三方网关的Referer 做了安全限制!
//通过微信api downloadFile下载然后通过openDocument打开就ok
wx.downloadFile({
url: 'url',
header: {
'Content-type': 'application/pdf'
}
}).then(res => {
wx.openDocument({
filePath: res.tempFilePath,
fileType: 'pdf',
success: res => {
console.log(res)
},
fail: () => {
wx.showToast({
title: '业务系统繁忙,请稍后重试',
icon: 'none',
mask: true,
duration: 3000
});
}
})
})
微信api downloadFile 报错状态码403 | 400
搞了好久才确定是referrer的问题(这个是网关的坑,一般都是第三方的referrer拦截了)
- 方案二
- 新建一个H5页面 在H5 里面调用下载pdf的接口 如下图
// 这样可以直接
$('iframe').attr('src', `data:application/pdf;base64,${file}` )
如果返回的是这样 (如下图)
- 第一种处理方式 进行base64转换
// pdf 接上面转换完的变量pdf (这样就可以直接看到结果了)
let base64 = `data:application/pdf;base64,${window.btoa(pdf)}`
$('iframe').attr('src',base64)
- 第二种处理方式 进行blob转换(收集一下处理方式,小程序内不好使用)
// pdf 接上面转换完的变量pdf (这样就可以直接看到结果了)
var binary = pdf.replace(/\s/g, '')
var len = pdf.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
var blob = new Blob([view], {
type: "application/pdf"
});
var url = URL.createObjectURL(blob);
$('iframe').attr('src', url)
言归正转 拿到base64字符串后通过jssdk的方法传给小程序
// 这里的base64不要带前缀 不要带前缀
wx.miniProgram.postMessage({ data: base64})
setTimeout(() => {
wx.miniProgram.navigateBack({})
},1500)
小程序拿到后 将base64 写入一个临时文件 然后打开就ok了
//怎么拿数据? 肯定在你的小程序写web-view 标签的页面中拿啊!直接存入缓存 或者看你的骚操作
let base64 = wx.getStorageSync('base64')
// 重要的事说三遍base64 不要私自加前缀
const arrayBuffer = wx.base64ToArrayBuffer(base64) //(该方法已不维护)
let fs = wx.getFileSystemManager()
fs.writeFile({
filePath: `${wx.env.USER_DATA_PATH}/hello.pdf`,
data: arrayBuffer,
encoding: 'binary',
success(res) {
wx.openDocument({
filePath: `${wx.env.USER_DATA_PATH}/hello.pdf`,
fileType: 'pdf',
success: res => {
console.log(res)
}
})
}
})