前端blob文件下载方法

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 };
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值