How to set the filename for a downloadable file in laravel?

by lindsey.homenick , in category: PHP General , 7 months ago

How to set the filename for a downloadable file in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 7 months ago

@lindsey.homenick 

To set the filename for a downloadable file in Laravel, you can use the Response object's header method. Here's an example:

1
2
3
4
5
6
7
8
9
use IlluminateSupportFacadesResponse;

public function downloadFile()
{
    $filePath = public_path('path/to/file.txt'); // Replace with your file path
    $fileName = 'custom_filename.txt'; // Replace with the desired filename

    return Response::download($filePath, $fileName)->header('Content-Disposition', 'attachment');
}


In this example, the downloadFile function downloads the file located at the given file path ($filePath) with the desired filename ($fileName). The header method is used to set the Content-Disposition header with the value 'attachment', which prompts the browser to download the file instead of displaying it.