下载文件(fetch)(js)

该代码段展示了如何在前端使用fetchAPI进行POST请求,将数据序列化并传递给后台,然后根据响应头获取文件名,创建可读流,处理文件内容,最后利用a标签实现文件下载。关键点包括设置请求头、解析Content-Disposition及创建Blob对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

let filename = '';
const anaExport = (data) => {
  return fetch('/export', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8',
      // 请求头设置:比如说下面这个是给后台传递token信息
      'token': window.localStorage.getItem('token') || ''
    },
    // 给后台传递的数据,这个得自己手动json序列化它
    body: JSON.stringify(data)
  }).then(res => {
  	// 响应头里面获取文件信息,注意:如果发现文件名字不对,看看这个响应头字段
    const contentDisposition = res.headers.get("content-disposition")
    if (res.status !== 200 || !contentDisposition) return message.error('导出失败');
    // 解码,下载后的文件名字
    filename = decodeURIComponent(contentDisposition?.split('=')?.[1] || '')
   
    const reader = res.body?.getReader();
    return new ReadableStream({
      start(controller) {
        function push() {
          reader?.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            controller.enqueue(value);
            push();
          })
        }
        push();
      }
    });
  })
    .then(stream => {
    	// content-type 这个改成接口响应头的content-type就行了。浏览器控制台network(网络)中的response ...(响应标头)里面的content-type
      const res = new Response(stream, { headers: { "Content-Type": "application/zip" }});
      res.blob().then((result) => {
        const file = new Blob([result]);
        // 把二进制数据生成对应的url地址(缓存地址)
        const objectUrl = URL.createObjectURL(file)

		// 以下为常规操作:创建 a 标签,然后进行下载文件
        const a = document.createElement("a")
        document.body.appendChild(a)
        a.style = "display: none"
        a.href = objectUrl
        a.download = filename.replace(/['\"']/img, '')
        a.click()
        window.URL.revokeObjectURL(objectUrl)
        document.body.removeChild(a);
        // ------------------------
      })
    })
    .catch(e => {
      console.error(e);
    });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值