【问题标题】:How to download excel in response from api react.js如何从api react.js下载excel以响应
【发布时间】:2021-08-23 10:17:18
【问题描述】:

我的 api 像这个演示一样响应 [URL][https://mytutari.com/webservices/contract/exportcallnote/10377431] 如果我点击 url 它会自动下载。但是当我尝试在 axios 响应中使用 POST 请求发布一些数据时,我得到了如何处理。 API 响应

> PKk)S docProps/PKk)SéÙ£docProps/app.xmlÏ1ƒ0ཿB²kl‡R$êR:w°ÝCrjÀÜIrý÷M)Ô½ããÁÇ{ª]ý”-¢#¬Å±(EhÈ:jñènùEd‘5Z=B-6ˆ¢mêh†Àb–Œµ™çJÊhFð:©ÆÔô¼æÃ
> ©ï+™—dy*˳„•-Ø|þâ+Vÿ‹Z2Ÿ}ñÙmsòÕë©sšRÉ=(¹ßhÞPKk)S…]ØÓ
> docProps/core.xmlm‘ËNÃ0E÷|Eä}b;¨²’t*Ø ÎZÄÙ¦iùz’´
> uçñ=>šñ‹­n“ ú ¬)  ÏIÐH[+Ó”äyµLç$  L
> ­5X’²¨.PKk)S  docProps/PKk)SéÙ£docProps/app.xmlÏ1ƒ0ཿB²kl‡R$êR:w°ÝCrjÀÜIrý÷M)Ô½ããÁÇ{ª]ý”-¢#¬Å±(EhÈ:jñènùEd‘5Z=B-6ˆ¢mêh†Àb–Œµ™çJÊhFð:©ÆÔô¼æÃ
> ©ï+™—dy*˳„•-Ø|þâ+Vÿ‹Z2Ÿ}ñÙmsòÕë©sšRÉ=(¹ßhÞPKk)S…]ØÓ
> docProps/core.xmlm‘ËNÃ0E÷|Eä}b;¨²’t*Ø ÎZÄÙ¦iùz’´
> uçñ=>šñ‹­n“ ú ¬)  ÏIÐH[+Ó”äyµLç$  L ­5X’²¨.

API 调用

 ```const formData = new FormData();
formData.append("DealerID", DealerID);
formData.append("FomDate", fromdate);
formData.append("ToDate", toDate);
formData.append("FixedDateParameter", FixedDateParameter);
formData.append("export_type", export_type);
//api
const dashboardexport_response = await dashboardexport({ formData });```

仪表板导出

  let url = API + "/dashboard/dashboardexport";

  formData.append("pcp_user_id", pcp_user_id);
  formData.append("role_id", role_id);
  formData.append("user_id", user_id);
  try {
    const response = await axios.post(url, formData, { header });
    return response.data;
  } catch (error) {
    throw Error(error);
  }
};```
 

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    你可以这样做:

    axios.post(url, {
        method: 'GET',
        responseType: 'blob', // important
    }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `${Date.now()}.xlsx`);
        document.body.appendChild(link);
        link.click();
    });
    

    source

    【讨论】:

    • 你拯救了我的一天,谢谢
    【解决方案2】:
    import axios, { AxiosRequestConfig } from 'axios';
    import fs from 'fs';
    
    export const downloadXLSFile = async () => {
        
        // Its important to set the 'Content-Type': 'blob' and responseType:'arraybuffer'.
        const headers = {'Content-Type': 'blob'};
        const config: AxiosRequestConfig = {method: 'GET', url: URL, responseType: 'arraybuffer', headers};
        
        try {
            const response = await axios(config);
            
            const outputFilename = `${Date.now()}.xls`;
    
            // If you want to download file automatically using link attribute.
            const url = URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', outputFilename);
            document.body.appendChild(link);
            link.click();
    
            // OR you can save/write file locally.
            fs.writeFileSync(outputFilename, response.data);
        } catch (error) {
            throw Error(error);
        }
    }
    

    【讨论】:

      【解决方案3】:

      值得注意的是,其他答案忘记在下载后从页面中删除链接元素。

      const url = window.URL.createObjectURL(new Blob([data.data]));
      const link = document.createElement('a');
      
      link.href = url;
      link.setAttribute(
          'download',
          `${Date.now()}.xlsx`,
      );
      
      document.body.appendChild(link);
      link.click();
      
      link.remove();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 2020-02-08
        • 2020-05-22
        • 1970-01-01
        • 2021-08-19
        • 1970-01-01
        • 2018-09-01
        相关资源
        最近更新 更多