【发布时间】:2020-12-16 00:41:39
【问题描述】:
我正在尝试使用 axios 从服务器下载 docx 文件。下载的文件比原始文件大,并且出现损坏,无法打开。问题不在于用于下载的 servlet,因为如果我直接在浏览器中使用该链接,它会完美下载。
我遇到了这个链接并尝试过,但没有成功。请让我知道我可能做错了什么。感谢你的帮助。 Download binary file with Axios
axios({
method: "GET",
url: "https://example.com/apps/GetFile?file=test.docx", //
responsetype: "blob",
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Content-Type': 'application/json'
}
}
}).then(function(response) {
const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', 'test.docx');
document.body.appendChild(link);
link.click();
})
.catch(function(error) {
alert(error);
});
【问题讨论】:
-
Access-Control-Allow-Origin是一个 response 标头,它必须来自服务器。它不属于您的请求 -
没关系,这不是这里的问题。
-
你想要在 Axios 配置中的设置是
responseType,而不是responsetype -
完美!那个修正奏效了。谢谢菲尔。