一般先获取文件名称,再去执行下载
// 先获取文件名
const fileName = extractFilename(res.headers['content-disposition'] || '');
export function extractFilename(contentDisposition: string) {
// 正则表达式匹配 'filename=' 后面的任意字符直到遇到 ';' 或字符串结束
const filenameRegex = /filename=([^;]+)/;
const matches = filenameRegex.exec(contentDisposition);
if (matches && matches[1]) {
// 去除可能的引号,并返回文件名
return matches[1].replace(/['"]/g, '').trim();
}
return null; // 如果没有匹配到,返回 null
}
拿到 下载路径 (必需) 和名称 后,前端执行以下代码
1. 一般下载
export function downloadFile(url: string, fileName: string) {
const link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('target', '_blank');
fileName && link.setAttribute('download', fileName);
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
2.流下载
// 下载流
export function downloadStream(stream: Blob | null, fileName: string) {
if (stream) {
const href = URL.createObjectURL(stream);
const link = document.createElement('a');
link.href = href;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(href);
} else {
window.$message?.error('下载失败');
}
}
3.二进制文件
/**
* 二进制文件
* @param steam 文件流
* @param name 导出的文件名
* @param format 导出的文件格式
*/
export function download(steam: Blob, name: string, format?: string) {
const blob = new Blob([steam], { type: format });
const link = document.createElement('a');
const href = URL.createObjectURL(blob);
link.href = href;
link.download = name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下载完成-移除元素
window.URL.revokeObjectURL(href); // 释放blob对象
}
以上