如何使用 axios 下载包含多种类型文件的 zip [英] How do i download a zip with multiple types of files with axios
问题描述
在我的 vueJs 应用程序中,我有以下 axios POST api 调用,假设返回我希望保存在 .zip 文件夹中的多个文件.但是,当我使用以下 axios 方法时,我无法打开我的 zip 文件,并且出现错误,提示我的文件夹.zip 无效".
In my vueJs application i have the following axios POST api call that is suppose to return multiple files that i wish to save on a .zip folder. however when i use the following axios method i can't open my zip and an error occurs saying that "my folder.zip is invalid".
如何正确下载 response.data?
How do i properly download the response.data?
这是方法.我在原始调用正文中发送了一些所需的信息,并发送了一个需要上传的文件,以便我可以获取需要下载的其他文件.
Here is the method. I send a few needed information in my raw call body and a file that is needed to be uploaded so i can get the other files that i need to download.
upload() {
console.log("uploading")
let formData = new FormData();
let gerarMenus = "on";
let zipName= "test";
let var1= "on";
let var2= "on";
let var3= "on";
let var4= "on";
this.files.forEach((f,x) => {
formData.append('file'+(x+1), f);
});
formData.append('zipName', zipName);
formData.append('var1', var1);
formData.append('var2', var2);
formData.append('var3', var3);
formData.append('var4', var4);
axios
.post("/myUrl/downloadFile", formData)
.then((response) => {
console.log(response.data)
const url = window.URL.createObjectURL(new Blob([response]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', zipName+ '.zip');
document.body.appendChild(link);
link.click()}
).catch(e => {
console.error(e);
});
我尝试了 tony19 的回答,但我仍然遇到同样的错误.不确定它是否有帮助,但我想得到多个 xml 和 sql 文件.
I tried tony19's answer but i still get the same error. Not sure if it is any help but i am suppose to get multiple xml and sql files.
这是我的 console.log() 中的 response.data 打印件:
here's a print of response.data in my console.log():
推荐答案
尝试在您的请求中将 responseType
选项设置为 blob
:
Try to set a responseType
option to blob
in your request:
axios
.post("/myUrl/downloadFile", formData, {
responseType: 'blob'
})
并在 Blob 构造函数中使用 response.data
就像@tony19 已经提到的那样.
And use response.data
in a Blob constructor as @tony19 already mentioned.
这篇关于如何使用 axios 下载包含多种类型文件的 zip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!