首页 > 解决方案 > Axios POST Request Decodes Response as Wrong Encoding

问题描述

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.

标签: javascriptrestaxios

解决方案


在 Axios 和 Vue.js 中下载二进制文件时,我遇到了完全相同的问题。该文件为 9.7MB,但 axios 接收它为 18.3MB。文件大小已在 chrome 的开发人员控制台中显示为 18.3MB,用于带有 console.log(response) 的“数据”属性。从文件内容可以看出,编码不同。

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

我还尝试了https://stackoverflow.com/a/53372599/7921366提出的解决方案,responseType: 'arraybuffer', responseEncoding: 'binary'但无济于事。


推荐阅读