Blackmore
Blackmore

Reputation: 31

How to download a file using axios?

I am using Vue js to make a post request to a backend API. The response data should be downloaded into a zip file. Though the file downloads as a zip file, I get an error when I try to open the file. Error message: Windows cannot open the folder. The compressed (zipped) folder "........\test.zip" is invalid.

Here is my vue code

let config = {
    Headers: {
      "Content-Type": "multipart/form-data",
      responseType: "blob",
    },
  };
  axios
    .post(
      `http://localhost:5050/generator`,
      this.forms,
      config
    )
    .then((response) => {
      const zipName = "test";
      this.forms = {
        productName: "",
        companyName: "",
      
      };
      const url = window.URL.createObjectURL(
        new Blob([response.data], { type: "application/zip" })
      );
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", zipName + ".zip"); 
      document.body.appendChild(link);
      link.click();
    });

Update

I used this code

function _base64ToArrayBuffer(base64) {
          var binary_string = window.atob(base64);
          var len = binary_string.length;
          var bytes = new Uint8Array(len);
          for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
          }
          return bytes.buffer;
        }

to convert it to a UintArray. I received another error 'DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.'

Upvotes: 1

Views: 3831

Answers (1)

IVO GELOV
IVO GELOV

Reputation: 14259

You can use FileSaver:

import SaveAs from "file-saver";

.....
.then((response) => 
{
  ....
  saveAs(new Blob([response.data], { type: 'application/octet-stream' }), response.filename, { autoBOM: false });
}

Upvotes: 1

Related Questions