How to download image in Laravel 8

How to download image from storage in Laravel 8

Posted by Ervin Adams on October 22, 2021

How to download image in Laravel 8

How to download image from storage in Laravel 8

Posted by Ervin Adams on October 22, 2021

In this tutorial you will be shown how to download a file in Laravel 8.

Step 1. Create controller by executing command.

php artisan make:controller DownloadFileController

Go to "app/Http/Controller/DownloadFileController" and edit the controller.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class DownloadFileController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return BinaryFileResponse
     */
    function getFile($filename){
        $path = storage_path('app/public/'.$filename);
        return response()->download($path);
    }
}

Step 2 Create routes

Go to "routes/web" and edit file

use App\Http\Controllers\DownloadFileController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () { return view('home');});

Route::get('get/{filename}', [DownloadFileController::class, 'getFile'])->name('getfile');

Step 3 Create view

Go to "resources/views" and create home.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Wecode101 download file</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

        <style>
            body {
                font-family: 'Nunito', sans-serif;
            }
        </style>
    </head>
    <body class="antialiased">
        <div class="text-center align-items-center mt-5">
            <h1>Download File</h1>
            <a class="btn btn-primary mt-2" href="{{route('getfile', 'lr-file.png')}}">Download file</a>
        </div>
    </body>
</html>

You should now be able to download a file.

If you wish to download this tutorial go to https://github.com/wecode101/download-file-laravel-8

This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question