Download 前端文件下载方法
import axios from 'axios';
export function useFileDownload() {
const downloadFile = async (url, data, filename) => {
try {
const response = await axios({
method: 'post',
url:url,
data,
responseType: 'blob',
});
// 尝试从响应头获取文件名
let finalFilename = filename;
const contentDisposition = response.headers['content-disposition'];
if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
if (filenameMatch && filenameMatch[1]) {
finalFilename = filenameMatch[1];
}
}
// 处理可能的编码文件名(如UTF-8编码)
if (finalFilename.includes('%')) {
finalFilename = decodeURIComponent(finalFilename);
}
const blob = new Blob([response.data]);
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', finalFilename);
document.body.appendChild(link);
link.click();
// 清理
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
}, 100);
return true;
} catch (error) {
console.error('文件下载失败:', error);
return false;
}
};
return { downloadFile };
}
1万+

被折叠的 条评论
为什么被折叠?



