environment:
uni-app WeChat applet
Description of Requirement:
The front-end requests the back-end interface, the back-end returns the pdf file stream in base64 format , and the front-end obtains the data to open and view the pdf
Code:
1. Add interface response header configuration
responseType: 'arraybuffer'
2. Use the WeChat file management system to write the base64 format file stream returned by the backend interface to the mobile phone, and then open the preview
// 调用获取 pdf 文件流接口
await getReportDoc({ ...params }).then((data) => {
const fs = uni.getFileSystemManager()
const filePath = wx.env.USER_DATA_PATH + '/' + Date.now() + '.pdf' // wx.env.USER_DATA_PATH 为微信提供的保存文件路径
fs.writeFile({
filePath,
data: wx.base64ToArrayBuffer(data.data.replace(/[\r\n]/g, '')), // 将 base64 转为 arrayuffer
success (res) {
uni.openDocument({
showMenu: true,
fileType: 'pdf',
filePath,
success: function (res) {
console.log('打开文档成功')
}
})
},
fail (err) {
console.log('错误', err)
}
})
})
Here, the applet does not support Blob, so the response type responseType cannot be set to Blob. I checked a lot, and the above code is effective. If there are other ways, welcome to add