Home > Software engineering >  How do I force a file download in Laravel 9?
How do I force a file download in Laravel 9?

Time:12-16

I have a .exe that users must install for a piece of hardware on my website. I am currently storing this .exe in my storage/app/public folder and have ensured that both the file and the folders have permissions to be accessed.

I have run php artisan storage:link

And currently use:

public function Downloadfile(Request $request)
{
    Log::debug("DOWNLOADFILE");
    $path = storage_path().'\\app\\public\\'.'file.exe';
    Log::debug("Path ".$path);
    Log::debug(file_exists($path));
    
    return Storage::download($path);
}

This results in the following.

An image of a log file describing the results of the debug messages

The file EXISTS, as the logs say, but for some reason, when I try to download it, I cannot do so.

CodePudding user response:

The storage_path() function returns the fully qualified path to your application's storage directory.

Also, you want to return a response. For example, the download method can generate a response that forces the user's browser to download the file at the given path.

public function Downloadfile(Request $request)
{
    $path = storage_path('app/public').'/'.'file.exe';

    return response()->download($path);
}

CodePudding user response:

I think that you have your path wrong. You need to get rid of:

app/public

In the Laravel config/filesystems.php there is usually this:

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

So

The 'storage' sym link in the public folder is a sym link to storage/app/public.

php artisan storage:link

At least with my setup, my profile photos are in: public/profile-photos, and the url to those is:

storage/profile-photos/bIlkdsTMTJFjiBDoarcQcfxWutJ0BvktYDQ7dcjU.jpg

so you probably need:

C:\Usersxxx.source\repos\xxx\storage\file.exe

You just need to adjust the path. Try that.

  • Related