簡體   English   中英

axios 從后台按生成的文件名下載文件

[英]Axios download file by the generated filename from the backend

我正在使用Axios向我的后端發送POST請求。

后端生成一個名為testing.xlsxExcel文件。

我正在嘗試做的事情:

使用從后端生成的相同文件名執行此文件,我嘗試過Postman ,一切正常。

我嘗試過的:

axios.post(`${env.ENDPOINT}reports/sales/customers_statement`, {
    customers_id: form_data.customers_id,
    from_date: form_data.from_date,
    to_date: form_data.to_date,
  },{
    responseType: 'blob'
  }).then((res) => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    const file_name = `${new Date().toISOString().slice(0,10)}.xlsx`; // RENAME HERE
    link.href = url;
    link.setAttribute('download', file_name);
    document.body.appendChild(link);
    link.click();
    resolve(res.data);
  }).catch((e) => {
    reject(e);
  });

這工作正常,但它不會通過從服務器生成的文件名下載文件。

換句話說,我想向我的后端發送請求,以通過后端已經生成的文件名下載文件,就像我使用 Postman 發送請求一樣。

這是因為您將下載屬性設置為 file_name 值,該值與返回的文件名服務器不同

 const file_name = `${new Date().toISOString().slice(0,10)}.xlsx`; 

嘗試將以上更改為此

const contentDisposition = data.headers['content-disposition'];
const filename = contentDisposition.match(/filename=(?<filename>[^,;]+);/)[0]; 
link.setAttribute('download', file_name);

在后端

response.setHeader("Content-disposition", "attachment; filename="+ yourfilenamehere);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM