Download with wx.downloadFile({}) , then open the file with wx.openDocument({})
1. First request to the pdf path network address, and download the pdf to the local
2. Upload the local file to a temporary path and delete the local file
3. Open the file in the temporary path
Note : You need to configure the legal domain name of downloadFile in the developer management:
WeChat public platform-->Development management-->Development settings-->downloadFile legal domain name
openHandle() {
let that = this;
const fileExtName = ".pdf";
const randfile = new Date().getTime() + fileExtName;
const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`; // 定义一个临时路径
that.deletContract(); // 将本地文件删除
wx.downloadFile({
url: "", // 网络文件的地址
header: {
"content-type": "application/pdf",
Authorization: wx.getStorageSync("token"),
},
filePath: newPath,
success: function (res) {
const filePath = res.tempFilePath;
wx.openDocument({
filePath: newPath,
showMenu: true,
fileType: "pdf",
success: function (res) {},
});
},
fail: function (res) {
wx.hideLoading();
},
});
},
// 删除本地文件
deletContract() {
try {
let file = wx.getFileSystemManager();
file.readdir({
dirPath: `${wx.env.USER_DATA_PATH}`,
success: (res) => {
if (res.files.length > 2) {
file.unlink({
filePath: `${wx.env.USER_DATA_PATH}/${res.files[0]}`,
complete: (res) => {},
});
}
},
});
} catch (error) {}
},