Download file from backend laravel using vue as frontend

Viewed 1336

I have created controller in Laravel which contains following code

$doc = Document::find($id);
if (Storage::disk('local')->exists($doc->path)) {
      return Storage::disk('local')->get($doc->path);
}

In my frontend I'm using javascript to programatically download the file with following code (is it ok to use blob or there is any other way to do it?)

async downloadDocument() {   
  DocService.downloadDoc(this.document.id).then((response) => {  // Service that handles ajax call
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", this.document.name);
    document.body.appendChild(link);
    link.click();
    link.remove();
  });
},

I'm able to download and see contents of txt, php files but when I try to download image, pdf, etc files are downloaded but content of the files are empty or unreadable.

2 Answers

If someone comes across similar issue you can do following to solve it

Laravel/backend Code:

$path = storage_path() . '/app/' . $doc->path;
        return response()->download($path);

Define path of your file and response it with download()

Frontend Code:

async downloadDocument() {
  axios({
    url: "/api/documents/" + this.document.id,
    method: "GET",
    responseType: "blob", // important
  }).then((response) => {
    // Service that handles ajax call
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", this.document.name);
    document.body.appendChild(link);
    link.click();
    link.remove();
  });
},

},

Remember responseType is important, else your downloaded file(pdf, image) won't show any content.

Hope this answer can help someone.

Use the download() method witht the proper headers instead:

return Storage::download($doc->path, basename($doc->path), [
    'Content-Description' => 'File Transfer',
    'Content-Type' => mime_content_type($doc->path),
]);

In case you want to sent the file as raw text to the client and let it decide what to do with it:

return response(Storage::disk('local')->get($doc->path))->withHeaders([
    'Content-Description' => 'File Transfer',
    'Content-Type' => mime_content_type($doc->path),
]);
Related