Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file in Laravel using a URL to external resource

Tags:

php

laravel

I'm keeping all uploads on a custom, external drive. The files are being stored via custom API.

In Laravel 5.2, I can do this for a local file to download it:

return response()->download('path/to/file/image.jpg'); 

Unfortunately, when I pass a URL instead of a path, Laravel throws an error:

The file "https://my-cdn.com/files/image.jpg" does not exist

(the URL is a dummy of course).

Is there any way I can download the image.jpg file using Laravel's implementation or do I do this with plain PHP instead?

like image 437
lesssugar Avatar asked Aug 05 '16 14:08

lesssugar


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.

How do I get files in Laravel?

If you have file object from request then you can simply get by laravel function. $extension = $request->file->extension(); dd($extension); If you have file object from request then you can simply get by laravel function.


1 Answers

There's no magic, you should download external image using copy() function, then send it to user in the response:

$filename = 'temp-image.jpg'; $tempImage = tempnam(sys_get_temp_dir(), $filename); copy('https://my-cdn.com/files/image.jpg', $tempImage);  return response()->download($tempImage, $filename); 
like image 191
Limon Monte Avatar answered Sep 24 '22 03:09

Limon Monte