使用外部资源的URL在Laravel中下载文件 [英] Download a file in Laravel using a URL to external resource

查看:183
本文介绍了使用外部资源的URL在Laravel中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将所有上传内容保存在自定义的外部驱动器上.这些文件是通过自定义API存储的.

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

在Laravel 5.2中,我可以对本地文件进行下载:

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

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

不幸的是,当我传递一个URL而不是一个路径时,Laravel抛出了一个错误:

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

文件" https://my-cdn.com/files/image.jpg"不存在

(URL当然是虚拟的).

(the URL is a dummy of course).

有什么方法可以使用Laravel的实现下载 image.jpg 文件吗?或者我可以使用纯PHP来做到这一点?

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

推荐答案

没有魔术,您应该使用 copy() 函数,然后在响应中将其发送给用户:

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);

这篇关于使用外部资源的URL在Laravel中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆