1

I want to send a docx file to the client in the response of a get request:

Here's the Laravel controller code:

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 code:

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

It doesn't show any error. but downloads a corrupted 9bytes docx file.

Touha
  • 537
  • 2
  • 6
  • 13
  • Have you tried by changing your response type from `arrayBuffer` to `blob`? – IlGala Sep 27 '19 at 10:47
  • yes I tried. nothing changes. – Touha Sep 27 '19 at 10:50
  • Man dowloading from axios is a mess... I had a lot of problems too with PDF... I've followed [this answer](https://stackoverflow.com/a/50737567/2343305) and looking at your code, it seems that you followed it too... But I've never tried with .docx files... Maybe you should try with a stream download from the server side... – IlGala Sep 27 '19 at 10:57

1 Answers1

1

changing response.body to response.data did the job.

Touha
  • 537
  • 2
  • 6
  • 13