PHP Laravel:How to download files

Table of Contents

Table of Contents

Download files from Laravel application

In many websites with management interfaces, especially for services that analyze data and store data, you will often see the option to download files so that users can get the data they want to their computers.
Laravel also provides methods to download files, images, or data from databases into text files for exporting to the server in response to such operational needs. The following section will discuss the commonly used methods and how to export the contents of Array as a csv file.

workflow

  • Prepare the Controller for download processing: ExportController
  • Two types of file download methods.
    • 1: Storage::download()
    • 2: response()->download()
  • export the contents of Array as a csv file: response()->stream()

ExportController & web

First prepare ExportController, which has download_storage and download_response functions, and later use Storage::download() and response()->download() in these two functions respectively.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ExportController extends Controller
{

    public function download_storage(Request $request)
    {
        //...
    }

    public function download_response(Request $request)
    {
        //...
    }

}

Set up the relative routes in web.php.


Route::get('/export/download_storage', [ExportController::class, 'download_storage'])->name('export.download_storage');
Route::get('/export/download_response', [ExportController::class, 'download_response'])->name('export.download_response');

Method1. Storage::download($filePath, $fileName, $headers)

Prepare a test.png image file in the storage/app/public path under the root directory of your Laravel project.
Then use the Storage::download() method to download the image file.

public function download_storage(Request $request)
{
    $filePath = 'public/test.png';
    $fileName = 'test.png';
    $mimeType = Storage::mimeType($filePath);
    $headers = [['Content-Type' => $mimeType]];
    return Storage::download($filePath, $fileName, $headers);
}

Method2. response()->download($filePath, $fileName, $headers)

In the same way, prepare the test.png image file in the storage/app/public path in the root directory of the Laravel project.
Use the response()->download() method to get the file and download it.

public function download_response(Request $request)
{
    $filePath = Storage::path('public/test.png');
    $fileName = 'test.png';
    $mimeType = Storage::mimeType($filePath);
    $headers = [['Content-Type' => $mimeType]];
    return response()->download($filePath, $fileName, $headers);
}

export the contents of Array as a csv file

Here use the response()->stream() method and fopen() and fputcsv() in callback to make a csv file.

public function csv_stream(Request $request)
{
    $response_headers = [
            'Content-type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename=export.csv',
            'Pragma' => 'no-cache',
            'Expires' => 0,
        ];
        
        $results = [
            ['id', 'name', 'class'],
            [1, 'John', '1-A'],
            [2, 'Tom', '1-B'],
            [3, 'Mary', '2-A'],
            [4, 'May', '2-B'],
        ];
        $callback = function () use ($results) {
            $resource = fopen('php://output', 'w');
            foreach ($results as $row) {
                fputcsv($resource, $row);
            }
            fclose($resource);
        };
        return response()->stream($callback, 200, $response_headers);
}

Don't forget to set the route in web.php.

Route::get('/export/csv_stream', [ExportController::class, 'csv_stream'])->name('export.csv_stream');