html a标签download下载后文件名多了_横杠_
一般下载都是get请求,window.open直接下载,但是遇到批量下载时就只能用post处理后端返回的文件流,文件名称从response的Headers中获取。
之前前端下载的fileName都是写死的, 现在业务要求要展示后端返回的文件名.
const fileName = decodeURIComponent((response.headers.get('Content-Disposition').split('='))[1]);
// console.log('fileName'); "111海报"
fileName打印出来是“111海报”,但下载后的文件名却多了下滑杠 “ _111海报.zip”
细心点会发现从headers获取到的fileName是双引号 “”,而link.download是单引号,所以下载的时候浏览器会把多出来的双引号转换成下划线。
解决方案:去掉双引号 fileName.replace(new RegExp(‘"’, ‘g’), ‘’);
// 请求处理函数
function responseHandledownLoad<T extends BaseApiResponse>(response: Response) {
return Promise.resolve(response)
.then((res) => resposneStateHandler(res))
.then((res) => parseResponseData(res))
.then((res) => {
const contentType = response.headers.get('content-type');
const fileName = decodeURIComponent((response.headers.get('Content-Disposition').split('='))[1]);
let blob;
if (contentType?.includes('application/zip')) {
blob = new Blob([res], { type: 'application/zip' });
} else if (contentType?.includes('image/jpeg')) {
blob = new Blob([res], { type: 'image/jpeg' });
}
const objectUrl = URL.createObjectURL(blob); // 创建URL
const link = document.createElement('a');
link.href = objectUrl;
link.download = fileName.replace(new RegExp('"', 'g'), '');
link.click(); // 下载文件
URL.revokeObjectURL(objectUrl); // 释放内存
return Promise.reject(response);
});
}
// downLoadpost请求
export const downLoadpost = <T extends BaseApiResponse>({ url, data }: { url: string; data: any }) => fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
Language: i18n.language,
'Access-Control-Allow-Origin': '*',
},
responseType: 'blob',
body: JSON.stringify(data),
})
.then((response) => responseHandledownLoad<T>(response))
.catch((ex) => Promise.reject(ex));