使用laravel的docx文件下载系统-vuejs

时间:2019-09-27 10:39:04

标签: php laravel vue.js

我想在获取请求的响应中向客户端发送docx文件:

这是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);
}

它没有显示任何错误。但会下载损坏的9bytes docx文件。

1 个答案:

答案 0 :(得分:0)

response.body更改为response.data即可完成工作。