两种常用的react 下载文件方法

总结了两种常用的react 下载文件到本地浏览器方法

方法1:使用a 标签的href属性设置为文件路径,就可以触发下载行为。

     <a
        key={
    
    record.id}
        href={
    
    `/lib/attach/match/download?fileUrl=${
      
      record.fileUrl}`}
       >
          附件下载
      </a>

方法2:如果后端传的是文件流,则需要解析文件流,然后通过a标签下载

// 下载接口
export async function exportDetail(){
    
    
  const url = `/vip/exportDetail`;
  return request(url,{
    
    
    method: 'GET',
    responseType: 'blob', // 必须加这属性,说明是文件流
  });
}

// 下载按钮点击事件
const exportExcel = async () => {
    
    
      setExportExcelLoading(true);
      const res = await exportDetail(); //调用接口
      if (res) {
    
    
        const url = window.URL.createObjectURL(new Blob([res]));
        const link = document.createElement('a'); //创建a标签
        link.style.display = 'none';
        link.href = url; // 设置a标签路径
        link.download = '名单列表.xls'; //设置文件名, 也可以这种写法 (link.setAttribute('download', '名单列表.xls');
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href); // 释放 URL对象
        document.body.removeChild(link);
      }
      setExportExcelLoading(false);
  };

猜你喜欢

转载自blog.csdn.net/baidu_25051161/article/details/123661166