背景:后端接口,返回二进制文件流
小程序预览文件
//file 文件流,filename 文件名
let { file, filename } = this.data;
const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
fs.writeFile({
// 写文件
filePath: wx.env.USER_DATA_PATH + "/" + filename, // wx.env.USER_DATA_PATH 指定临时文件存入的路径,后面字符串自定义
data: file,
encoding: "binary", //二进制流文件必须是 binary
success(res) {
wx.openDocument({
// 新开页面打开文档
filePath: wx.env.USER_DATA_PATH + "/" + filename, //拿上面存入的文件路径
showMenu: true, // 是否显示右上角菜单(提供下载到手机文件夹、分享等功能)
success: function (res) {
setTimeout(() => {
wx.hideLoading();
}, 500);
},
});
},
});
H5 下载二进制流文件,预览pdf可以浏览器直接打开
// 将二进制流转为blob
let { file, filename } = this.data;
const blob = new Blob([file], {
type: "application/octet-stream",
});
if (typeof window.navigator.msSaveBlob !== "undefined") {
// 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
window.navigator.msSaveBlob(blob, decodeURI(filename));
} else {
// 创建新的URL并指向File对象或者Blob对象的地址
const blobURL = window.URL.createObjectURL(blob);
// 创建a标签,用于跳转至下载链接
const tempLink = document.createElement("a");
tempLink.style.display = "none";
tempLink.href = blobURL;
tempLink.setAttribute("download", decodeURI(filename));
// 兼容:某些浏览器不支持HTML5的download属性
if (typeof tempLink.download === "undefined") {
tempLink.setAttribute("target", "_blank");
}
// 挂载a标签
document.body.appendChild(tempLink);
tempLink.click();
document.body.removeChild(tempLink);
// 释放blob URL地址
window.URL.revokeObjectURL(blobURL);
}