html a标签download下载后文件名多了_横杠_

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));
  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值