英文:
trying to download file directly from response of an api
问题
以下是要翻译的内容:
我有一个 API 响应,它返回一个 xlsx 文件作为响应。
API 是在按钮点击时触发的,我需要在响应上下载它。
每个 API 调用都经过一个服务,该服务会将令牌附加到 URL 以进行身份验证,这基本上意味着我不能使用像这个这里提到的方法那样的方法。我得到的响应是像这样(在调试时的响应)。我尝试过
a.href = window.URL.createObjectURL(response)
和
a.href = window.URL.createObjectURL(new blob([response]))
并尝试下载,但电子表格损坏了(我知道文件没问题,因为 Swagger 正确返回文件)。
我如何才能得到这个文件,就像在 Swagger 中那样像这样,以便我可以在 a.click()
中下载。
这是我的API,来自 .NET
提前感谢您。
英文:
I have an api response which return a xlsx file as response.
the api is triggered on button click and I need to download it as on response.
every api call is gone through a service which handles appends token to the url for authentication purposes.which basically means that I cannot use methods like this the one mentioned here. the response I am getting is like this ( response when debugged ). I have tried
a.href = window.URL.createObjectURL(response)
and
a.href = window.URL.createObjectURL(new blob([response]))
and tried downloading but but spreadsheet is corrupted ( I know the file is fine sice swagger returns the file properly).
how do I get this file as that of in swagger like this so that i can download in a.click()
.
this is my api from dot net
thank you in advance.
答案1
得分: 0
你可以尝试使用FileSaver.js
库来下载文件。以下是示例代码:
import FileSaver from 'file-saver';
// 调用您的API以获取响应
axios.get('/PrintWorkSheet', { responseType: 'arraybuffer' }).then((response) =>
{
// 从响应数据创建Blob对象
const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// 使用FileSaver.js将Blob保存为文件
FileSaver.saveAs(blob, 'WorkSheet.xlsx');
})
.catch((error) => {
console.log(error);
});
如果您有任何问题,请随时提问。
英文:
You can try using the FileSaver.js
library to download the file.
Here is the sample code:
import FileSaver from 'file-saver';
// Call your API to get the response
axios.get('/PrintWorkSheet', { responseType: 'arraybuffer' }).then((response) =>
{
//Create a Blob object from the response data
const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// Use FileSaver.js to save the Blob as a file
FileSaver.saveAs(blob, 'WorkSheet.xlsx');
})
.catch((error) => {
console.log(error);
});
答案2
得分: 0
问题出在axios实例上。
我已将响应类型添加到请求头中,问题得以解决。
responseType: "blob",
这是根本原因。之后,我能够使用'Klian'在评论中提供的响应下载文件。
英文:
The issue was with the axios instance.
I have added response type to the request header, the issue was solved.
responseType: "blob",
this was the root cause. After that I was able to download the file with response provided by 'Klian' in the comments to my question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论