Laravel + Image Intervention : Force download of file that is not saved

ぐ巨炮叔叔 提交于 2019-12-10 11:00:32

问题


I want to simply upload files , resize them and then force a download for every uploaded file. I do not want to save the files.

Resizing etc. works fine, however I cannot manage to force the download of the new file.

$content = $image->stream('jpg');

return response()->download($content, $name);

The shown snippet results in

is_file() expects parameter 1 to be a valid path, string given

Most probably because $content is not a path but the actual data.

Is there a way to enforce the download without saving it first?


回答1:


Try this:

$url = "https://cdn.psychologytoday.com/sites/default/files/blogs/38/2008/12/2598-75772.jpg";
$name = 'happy.jpg';

$image = Image::make($url)->encode('jpg');
$headers = [
    'Content-Type' => 'image/jpeg',
    'Content-Disposition' => 'attachment; filename='. $name,
];
return response()->stream(function() use ($image) {
    echo $image;
}, 200, $headers);

Here's what we're doing. We're using Intervention Image to encode that image into the correct file type format for us. Then we're setting the browser headers ourselves to tell the browser what type of file it is and that we want the browser to treat it as a downloadable attachment. Lastly, we return the response using Laravel's stream() method and use a closure. We tell the closure it has access to the encoded data of the image with use ($image) and then we simply echo that raw data onto the page. From there we tell the browser the HTTP code is 200 (OK), and then give it our headers to tell the browser what to do.

Your problem was that Laravel's handy download() method is expecting it to be a file on the file system. So we have to stream it and manually set the headers ourselves.

You will need to write some additional code to handle different file extensions for the encode() method Intervention uses as well as the Content-Type returned. You can find a list of all available mime types here.

I hope this helps.



来源:https://stackoverflow.com/questions/42643956/laravel-image-intervention-force-download-of-file-that-is-not-saved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!