Laravel how to download a file

Laravel makes it easy to download files with an example: learn how to use StreamedResponse and File download methods.

Downloading a File in Laravel

Downloading a file in Laravel is quite straightforward. Below is an example of how to download a file using the Response::download() method. First, you will need to create a route to the file you want to download. This route should return a response that contains the file you want to download.


Route::get('/download-file', function(){
    return Response::download('/path/to/file.zip');
});

This route should return a response with a file name, the path to the file, and the MIME type of the file. You can also specify a different file name for the download. To do this, pass an array as the second argument to the download method.


Route::get('/download-file', function(){
    return Response::download('/path/to/file.zip', 'my-custom-file-name.zip');
});

By default, the response type of the download method is application/octet-stream. You can also specify a different response type. To do this, pass an array as the third argument to the download method.


Route::get('/download-file', function(){
    return Response::download('/path/to/file.zip', 'my-custom-file-name.zip', ['content-type' => 'application/pdf']);
});

You can also set any other response headers you want by passing an array as the fourth argument to the download method. For example, if you want to set a cache-control header to the response, you can do so as follows:


Route::get('/download-file', function(){
    return Response::download('/path/to/file.zip', 'my-custom-file-name.zip', ['content-type' => 'application/pdf'], ['cache-control' => 'no-cache']);
});

That's all there is to it. With the Response::download() method, you can easily download files in your Laravel application.

Answers (0)