简体   繁体   中英

How do i download a zip with multiple types of files with axios

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".

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);
        });

EDIT: 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.

EDIT2: here's a print of response.data in my console.log(): 在此输入图像描述

In this line:

const url = window.URL.createObjectURL(new Blob([response])); // DON'T DO THIS
                                                 ^^^^^^^^

...you're creating an object URL to a blob of the entire Axios response object (including HTTP status code, headers, etc.), but you actually want the data property within it like this:

const url = window.URL.createObjectURL(new Blob([response.data]));

Try to set a responseType option to blob in your request:

axios
     .post("/myUrl/downloadFile", formData, {
          responseType: 'blob'
     })

And use response.data in a Blob constructor as @tony19 already mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM