【发布时间】:2020-01-27 16:21:56
【问题描述】:
我想向客户端发送一个 docx 文件作为 get 请求的响应:
这是 Laravel 控制器代码:
public function file($id)
{
$dlink = resource_path('temp/' . $id . '.docx');
$headers = [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];
return response()->download($dlink, $id . '.docx', $headers);
}
VueJS 代码:
axios.get(`${location.protocol}//${location.host}/api/download/${response.data}`,
{ responseType: "arraybuffer" }
)
.then(response => {
this.downloadFile(response);
})
.catch(err => alert(err));
downloadFile(response) {
var newBlob = new Blob([response.body], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
return;
}
const data = window.URL.createObjectURL(newBlob);
var link = document.createElement("a");
link.href = data;
link.download = "resume.docx";
link.click();
setTimeout(function() {
window.URL.revokeObjectURL(data);
}, 100);
}
它没有显示任何错误。但会下载损坏的 9 字节 docx 文件。
【问题讨论】:
-
您是否尝试将响应类型从
arrayBuffer更改为blob? -
是的,我试过了。没有任何变化。
-
从 axios 下载的人是一团糟……我也遇到了很多关于 PDF 的问题……我关注了this answer 并查看了您的代码,看来您也关注了它...但我从未尝试过使用 .docx 文件...也许您应该尝试从服务器端下载流...