Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create download link in Laravel

I am having problem creating a download link to download files via a Mobile App from Laravel Storage folder.

I did something like $link = Response::Download(storage_path()./file/example.png) but to no avail.

I moved the file to the public folder and used http://domain.com/file/example.png and asset('file/example.png') but to no avail.

I am getting 404 NOT FOUND ERROR

How do I solve this?

like image 721
BlackPearl Avatar asked Nov 17 '14 11:11

BlackPearl


People also ask

How do you make a Laravel file downloadable?

Downloading files in Laravel is even more simple than uploading. You can pass download() method with file path to download file. Same way, if you want to download file from the public folder, you can use download() method from Response class.


3 Answers

Take a look at the Laravel Helpers documentation: http://laravel.com/docs/4.2/helpers

If you want a link to your asset, you can do it like this:

$download_link = link_to_asset('file/example.png');

Edit

If the above method does not work for you, then you can implement a fairly simple Download route in app/routes.php which looks like this:

Note this example assumes your files are located in app/storage/file/ location

// Download Route
Route::get('download/{filename}', function($filename)
{
    // Check if file exists in app/storage/file folder
    $file_path = storage_path() .'/file/'. $filename;
    if (file_exists($file_path))
    {
        // Send Download
        return Response::download($file_path, $filename, [
            'Content-Length: '. filesize($file_path)
        ]);
    }
    else
    {
        // Error
        exit('Requested file does not exist on our server!');
    }
})
->where('filename', '[A-Za-z0-9\-\_\.]+');

Usage: http://your-domain.com/download/example.png

This will look for a file in: app/storage/file/example.png (if it exists, send the file to browser/client, else it will show error message).

P.S. '[A-Za-z0-9\-\_\.]+ this regular expression ensures user can only request files with name containing A-Z or a-z (letters), 0-9 (numbers), - or _ or . (symbols). Everything else is discarded/ignored. This is a safety / security measure....

like image 93
Latheesan Avatar answered Oct 07 '22 09:10

Latheesan


Updating answer for Laravel 5.0 and above:

<a href={{ asset('file/thing.png') }}>Thing</a>
like image 43
Dylan Pierce Avatar answered Oct 07 '22 08:10

Dylan Pierce


You do not need any route or controller.Just give it to anchor tag.

 <a href="{{URL::to('/')}}/file/example.png" target="_blank">
     <button class="btn"><i class="fa fa-download"></i> Download File</button>
 </a>
like image 1
rashedcs Avatar answered Oct 07 '22 08:10

rashedcs