下载文件流 文件名转码

下载文件,后端返回文件流,前端下载并读取后端返回文件名content-disposition

后端接口返回content-disposition:

 

前端读取文件名并下载

1.axios返回请求响应全部数据

service.interceptors.response.use((response: AxiosResponse) => {
  const result = response.data;
  const { config: { responseType } } = response;
  if (responseType === 'blob') {
    return response;
  }

2.接口调用返回中读取解码:decodeURI(fileName)

getExport().then((res:any) => {
          const fileName = res.headers['content-disposition'].split(';')[1].split('filename=')[1];
// 转换编译content-disposition的文件名:decodeURI
          downloadFile(decodeURI(fileName), res.data);
        });

3.文档流下载方法

export function downloadFile(fileName:string, content:Blob, unicode = 'application/octet-stream;charset=utf-8'):void {
  // const blob = new Blob([content], { type: unicode });
  if ('download' in document.createElement('a')) { // 非IE下载
    const downloadElement = document.createElement('a');
    let href = '';
    if (window.URL) {
      href = window.URL.createObjectURL(content);
    } else {
      href = window.webkitURL.createObjectURL(content);
    }
    downloadElement.href = href;
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    if (window.URL) {
      window.URL.revokeObjectURL(href);
    } else {
      window.webkitURL.revokeObjectURL(href);
    }
    document.body.removeChild(downloadElement);
  } 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值