需求
在线预览doc/docx/xls/xlsx/ppt/txt/pdf 的文件和图片
思路
- 将后台返回的二进制流,写入微信的文件管理器。
- 打开文件
苹果、安卓真机均可预览文件
1.点击文字预览
<view @tap="handleFileList(item, index)">点击文字预览</view>
2.将后台返回的二进制流,写入微信的文件管理器(getDownload此处用的是封装好的api接口,也可以直接wx.request({})直接在这里请求)
<script>
export default {
methods: {
//预览方法
handleFileList(item, index) {
let ossId = item.ossid;//文件ossid
let fileName = item.name;//文件名称
uni.showLoading({
title: "正在打开",
});
getDownload(ossId)
.then((response) => {
const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;//获取临时下载存储路径
try {
wx.getFileSystemManager().writeFileSync(
filePath,
response,
"binary"
);//获取全局唯一的文件管理器并写入
uni.hideLoading();
// 打开文件
uni.openDocument({
filePath: filePath,//路径
showMenu: true,
success: function (res) {
console.log("打开文档成功");
},
fail: function (err) {
uni.showToast({
icon: "none",
title: "打开文档失败",
});
console.error("打开文档失败", err);
},
});
} catch (e) {
console.error("写入文件时发生错误", e);
uni.hideLoading();
}
})
.catch((err) => {
console.error("获取文件流数据失败", err);
uni.hideLoading();
});
}
}
}
</script>
3.api.js
import config from "../config/config.js";
const request = config.request;
// 获取文件下载地址
export function getDownload(ids) {
return request({
url: `${ip}/resource/oss/download/` + ids,
method: 'GET',
responseType: "arraybuffer"
})
}
注:真机调试也是OK的。