Home > Software engineering >  Download tar file using Axios
Download tar file using Axios

Time:07-19

I have an API-endpoint that gives me a tar file with the Content-Type: application/x-tar, which is then being served to my frontend app using Express. I tried fetching this file using Axios with the responseType: 'blob' but I cannot open the binary without an error saying that's in an unsupported format. Here is what I'm trying:

// backend
const axiosRes = await axios.get(`${API}/file`,
    { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/x-tar' }, responseType: 'blob' }
  );
res.send({ data: axiosRes.data });

// frontend
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.tar');
document.body.appendChild(link);
link.click();

How can I get the file in real .tar format and send it to the frontend?

CodePudding user response:

Problem #1 - Axios only supports responseType: "blob" in the browser.

If your Express app needs to retrieve a binary file, use this

const axiosRes = await axios.get(`${API}/file`, {
  headers: { Authorization: `Bearer ${token}` }, // no data, no content-type
  responseType: "arraybuffer", // use instead of "blob"
});

Problem #2 - You are responding with JSON

Using this

res.send({ data: axiosRes.data });

will try and JSON stringify the binary file response which simply won't work. Instead, just send the raw response data

res.type(axiosRes.headers["content-type"]).send(axiosRes.data);
  • Related