javascript - 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.
解决方案
在 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'
但无济于事。
推荐阅读
- python - 字典到面向对象的转换
- reactjs - React Redux -> 为什么我得到 TypeError: state.item is not iterable
- python-3.x - 如何使用 TensorFlow 训练两塔模型?
- algorithm - NIce Subsequence - 最长递增子序列的变体
- redux - 登录后不导航到经过身份验证的页面
- r - 通过列选择将数据帧拆分为多个数据帧
- c++ - 为什么这个合并排序实现不能正常工作?
- r - 选择嵌套列表的一个元素并将其转换为 R 中的数据框
- r - 需要用固定均值 25 和 st 2 替换年龄中的 NA
- reactjs - lit-element 和 React 的主要区别