VueJS:axios:下载的文件已损坏,无法打开



我正试图使用axios从服务器下载一个docx文件。下载的文件比原始文件大,并且看起来已损坏,无法打开。问题不在于用于下载的servlet,因为如果我直接在浏览器中使用链接,它会被完美下载。

我偶然发现了这个链接,也尝试过,但没有成功。请告诉我我可能做错了什么。感谢你的帮助。使用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);
});

正如@Phil所指出的,这是由于responseType中的错误。应该是";responseType";,而不是";响应类型";。我需要更多地关注细节:(

您的代码应该是这样的:

axios({
method: "GET",
url: "https://example.com/apps/GetFile?file=test.docx", //
responseType: "blob",
config: {
headers: {
'Accept': 'application/pdf'
}
}
}).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);
});

我希望这能帮助你!

最新更新