1、后端提供接口下载返回文件流
2、前端设置:responseType: 'arraybuffer'
3、设置文件写入保存(打开预览文件)
const data = await $http.download("/sideline/api/delivery/part/export/userId/77171245921079296.xlsx?userId=77171245921079296").then((res) => {
const base64 = uni.arrayBufferToBase64(res.data);
// 获取文件名从响应头
let fileName = "download.xlsx";
// const contentDisposition = res.header["Content-Disposition"];
// if (contentDisposition) {
// const match = contentDisposition.match(/filename="?(.+)"?/);
// if (match) fileName = match[1];
// }
// 保存文件
// 获取文件系统路径
const fs = uni.getFileSystemManager();
const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
// 将 base64 写入文件
fs.writeFile({
filePath: filePath,
data: base64,
encoding: "base64",
success: () => {
console.log("文件保存成功", filePath);
uni.showToast({
title: "下载成功",
icon: "success",
});
uni.openDocument({
filePath: filePath,
fileType: 'xlsx',
success: () => {
console.log("打开文件成功");
},
fail: (err) => {
console.error("打开文件失败", err);
},
});
},
fail: (err) => {
console.error("文件保存失败", err);
uni.showToast({
title: "保存失败",
icon: "none",
});
},
});
}).catch((err) => {});