[英]Axios download file by the generated filename from the backend
I am using Axios to send POST
request to my backend.我正在使用Axios向我的后端发送
POST
请求。
The backend generate an Excel file with a name eg testing.xlsx .后端生成一个名为testing.xlsx的Excel文件。
Doing this file using the same filename generated from the backend and I have tried Postman and everything works fine.使用从后端生成的相同文件名执行此文件,我尝试过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);
});
This works fine but it doesn't download the file by the filename generated from the server.这工作正常,但它不会通过从服务器生成的文件名下载文件。
In other words I want to send request to my backend to download the file by the file name already generated from my backend like when I send request using Postman.换句话说,我想向我的后端发送请求,以通过后端已经生成的文件名下载文件,就像我使用 Postman 发送请求一样。
It is because you are setting the download attribute to file_name value which is different from the filename server returned这是因为您将下载属性设置为 file_name 值,该值与返回的文件名服务器不同
const file_name = `${new Date().toISOString().slice(0,10)}.xlsx`;
Try changing the above to this尝试将以上更改为此
const contentDisposition = data.headers['content-disposition'];
const filename = contentDisposition.match(/filename=(?<filename>[^,;]+);/)[0];
link.setAttribute('download', file_name);
In the backend在后端
response.setHeader("Content-disposition", "attachment; filename="+ yourfilenamehere);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.