0

When I make a post request to an API endpoint and the response contains binary data, the file saves incorrectly. The post request and save is as follows:

const response = await Vue.axios.post(apiEndpoint, { responseType: 'blob'});
saveAs(new Blob([response.data], { type: 'application/pdf' }),'test.pdf');

If I change the api endpoint and the axios request to a GET request, the file downloads correctly. After inspecting the saved file, the one from the POST is much larger and when doing a comparison you can tell the encoding is wrong.

How do I correct the above code to save the file correctly without changing the rest endpoint to a GET?

I have tried various response types and setting the Accept header but it doesn't seem to have an effect. I have also tried explicitly setting the charset to UTF-8 from the api and on the save call and it also doesn't work.

Mike
  • 562
  • 3
  • 15

1 Answers1

0

I have exactly the same issue with a file download in Axios and Vue.js for a binary file. The file is 9.7MB but axios receives it as 18.3MB. The file size is already shown as 18.3MB in the developer console of chrome for the 'data' property with console.log(response). What I can see from the file content is that the encoding is different.

const config: AxiosRequestConfig = {
      headers: {
        responseType: 'blob' as ResponseType,
      },
};
const response: AxiosResponse<Blob> = await axios.get<Blob>(url, config);
const filename = DownloadFileUtils.parseContentDisposition(response);
const blob = new Blob([response.data], {type: response.headers['content-type']});

I have also tried the proposed solution by https://stackoverflow.com/a/53372599/7921366 with responseType: 'arraybuffer', responseEncoding: 'binary' but with no avail.

Matthias Sommer
  • 1,070
  • 13
  • 28