简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM