Muhammad
Muhammad

Reputation: 634

How to specify the extension for a downloaded file Laravel 5.0

I am attempting to download a file when the user hits a route, and I was able to do so. However, when the user wants to download a docx or doc file, the file extension doesn't have .doc in it. To better ask my question, my code is below:

Route::get('resumeDownload', function() {
    $user = Auth::user();
    $path = $user->cv()->first()->path; //when the user uploads a document, i store
    //the path of it in the database
    $extension = explode(".", $path)[1]; //if the user uploaded a doc, returns .doc etc
    $uploaded = Storage::get($path); //I get it from my storage
    return (new \Illuminate\Http\Response($uploaded, 200))
           ->header('Content-Type', 'application/pdf');
});

This code works great when the user wants to download a pdf, however for a .doc file or a .docx file, the file which is downloaded has no extension. I also save the extension and can easily retrieve it, if that could help. Is there anyway to make this work for .doc, .docx, .pdf, and .txt?

Upvotes: 0

Views: 1069

Answers (1)

Javi Stolz
Javi Stolz

Reputation: 4753

You can use the Content-Disposition header to specify the name of the downloaded file but there is no need to manually create the download response. Laravel already has a built int function to generate a download response with the proper Content-Disposition header

$headers = ['Content-Type' => 'application/pdf'];
return response()->download($fileContent, 'filename.pdf', $headers);

Upvotes: 1

Related Questions