Search code examples
javascriptlaravelaxiosdownloadlaravel-filesystem

Download file from backend laravel using vue as frontend


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.


Solution

  • 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.