Download S3 file links in Laravel

Nitish Kumar picture Nitish Kumar · Oct 23, 2018 · Viewed 7.4k times · Source

I'm trying to build a small application in VueJs as frontend and Laravel as backend where I'm uploading files in my admin section to my aws-s3 while uploading the files I'm storing the link of that file in database. Every action is maintained by api calls, now I want to give option of these downloads to my end users so I'm making an axios call something like this:

downloadPDF(docs){
    const documents = {
        document: docs
    }
    axios.post('api/documents-download', documents, {headers: getHeader()}).then(response => {
        if(response.status === 200)
        {
            console.log('Downloaded')
        }
    })
},

And in my controller I'm having something like this:

public function download(Request $request)
{
    $headers = [
        'Content-Type' => 'application/pdf',
        'Content-Description' => 'File Transfer',
        'Content-Disposition' => "attachment; filename=filename.pdf",
    ];

    return response()->download($request->document, 'filename.pdf', $headers);
}

But it is throwing me error:

The file "https://s3-us-west-2.amazonaws.com/noetic-dev/2_Project/shiven-affordable-housing-surat/3_Document/Form+1/Form1.pdf" does not exist

This file clearly exists and made public as you can see above url shows the documents as linked.

Help me out with this. Thanks

Answer

Aleksandr Kopelevich picture Aleksandr Kopelevich · Apr 19, 2020

This code worked like a charm for downloading from S3 in Laravel 7 :

// $filePath should look like this: some-directory/filename.zip
return redirect(Storage::disk('s3')->temporaryUrl(
                    $filePath,
                    now()->addHour(),
                    ['ResponseContentDisposition' => 'attachment']
                ));

Credits to: https://sutherlandboswell.com/force-file-download-from-aws-s3-in-laravel/