// 点击文件列表中已上传的文件时的钩子
async handlePreview(scope, file) {
console.log(scope, file);
const res = await _commonFileManyDownloads({
filePath: file.response.data.uri,
});
let stringName = res.headers["content-disposition"].split(";")[1]; //一般来说,文件名字后端都在返回头里,前后端可以约定文件名前用 @ 符号分隔,便于取值,用其他符号也可以。
let fileNameEnd = stringName.split(".")[1]; //获取到了后缀名
let fileName = file.name.split(".")[0].slice(9); //获取到文件名(不含后缀)
fileName = file.name.split('.')[0] //一般来说后端返回的名字没有转码,需要前端解码utf-8,如果后端转了,就不用转。
let endFileName = `${decodeURIComponent(fileName) + "." + fileNameEnd}`;
let blob = new Blob([res.data], { type: "application/zip" }); //application/zip就是设置下载类型,需要设置什么类型可在标题二处查看,
const url = window.URL.createObjectURL(blob); //设置路径
const link = window.document.createElement("a"); // 创建a标签
link.href = url;
link.setAttribute("download", endFileName); // 给下载后的文件命名
link.style.display = "none";
link.click();
URL.revokeObjectURL(url); // 释放内存
},
多个文件下载(zip)
downloadZip(res.data, row.createBy + "提交附件", "zip");
封装文件如下
/**
* 下载压缩包文件
* @param {blob} fileArrayBuffer 文件流
* @param {String} filename 文件名称
* @param {String} fileType 文件格式
*/
export const downloadZip = (fileArrayBuffer, filename, fileType) => {
let data = new Blob([fileArrayBuffer], {
type:
fileType == "zip"
? "application/zip,charset=utf-8"
: "application/x-rar-compressed,charset=utf-8",
});
if (typeof window.chrome !== "undefined") {
// Chrome
var link = document.createElement("a");
link.href = window.URL.createObjectURL(data);
link.download = filename;
link.click();
console.log(data);
} else if (typeof window.navigator.msSaveBlob !== "undefined") {
// IE
var blob = new Blob([data], {
type:
fileType == "zip" ? "application/zip" : "application/x-rar-compressed",
});
window.navigator.msSaveBlob(blob, filename);
} else {
// Firefox
var file = new File([data], filename, {
type:
fileType == "zip" ? "application/zip" : "application/x-rar-compressed",
});
window.open(URL.createObjectURL(file));
}
};