Last updated on November 24, 2023
To download a file from the server in Laravel 8, you can use the response()->download()
method. Here’s an example of how to download a file:
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Response;
public function downloadFile()
{
$filePath = 'path/to/file.txt'; // Replace with the actual file path
if (Storage::exists($filePath)) {
$fileName = basename($filePath);
return response()->download(storage_path('app/' . $filePath), $fileName);
}
abort(404, 'File not found');
}
In the example above, we’re assuming that you have a file located at path/to/file.txt
in your Laravel application’s storage directory. You can replace this path with the actual path to your file.
The Storage::exists()
method is used to check if the file exists before downloading it. If the file exists, the response()->download()
method is used to create a response that prompts the user to download the file. The first argument of response()->download()
is the path to the file on the server, and the second argument is the desired file name for the downloaded file.
If the file does not exist, we return a 404 error response using the abort()
function.
Make sure to adjust the code according to your specific file location and requirements.