本文主要介绍小程序中从后台返回显示pdf文件的两种方法
情况一:后台直接给了一个pdf地址
使用wx.downloadFile会发起get请求,下载文件资源到本地,wx.openDocument打开
export const downPDF = function (obj) {
wx.downloadFile({
url: obj.url,
filePath: wx.env.USER_DATA_PATH + "/" + obj.name + ".pdf",
success(res) {
if (res.statusCode === 200) {
const tempFilePath = res.filePath
wx.openDocument({
filePath: tempFilePath,
showMenu: true,
fileType: "pdf",
success: function (res) {}
})
} else {
showAutoError("协议打开失败,请重新打开");
}
},
fail(res) {
showAutoError("协议下载失败")
}
})
};
情况二:后端提供一个接口,返回一个二进制流文件
后端提供了一个接口,返回一个二进制流文件,FileSystemManager.writeFile写入,wx.openDocument打开
var GET = function (url, params, isLoad = true, isShowError = true) {
return new Promise(function(resolve){
wx.request({
url: baseUrl + url + "?_locale=zh_CN&" + getPostData(params),
method: 'GET',
timeout: 30000,
header: {
'content-type': 'application/x-www-form-urlencoded',
},
responseType: 'arraybuffer',
success: function (res) {
if (res.statusCode == 200) {
resolve(res.data);
} else {
isShowError ? util.showError("系统繁忙,请稍后在试(" + res.statusCode + ")") : "";
}
},
fail: function (res) {
console.log(res)
util.showError("请求失败,请稍后再试")
},
complete: function (res) {
wx.hideLoading();
}
})
})
}
const finHetongDetail = function(data){
return new Promise(function(resolve){
resolve(GET('接口.json',data))
})
}
finHetongDetail(params).then(function (res) {
const FileSystemManager = wx.getFileSystemManager();
FileSystemManager.writeFile({
filePath:wx.env.USER_DATA_PATH + "/" +name + ".pdf",
data:res,
encoding:"binary",
success (res){
wx.openDocument({
filePath: wx.env.USER_DATA_PATH + "/" +name + ".pdf",
showMenu: true,
success: function (res) {
}
})
}
})
})