【问题标题】:download files from url in php laravel从 php laravel 中的 url 下载文件
【发布时间】:2021-11-06 04:51:26
【问题描述】:

我正在使用 php 版本 7.3 和 laravel 5.4

我有一个控制器函数fetchUrls,它返回一个包含 url 数据的 json 响应

public function fetchUrls($id) {
     $urlData = $this->service->fetchUrls($id);
  
     return $this->done(null, [
        'url_data' => $urlData
    ]);
}

在我的路由中使用这个控制器功能

Route::get('url-data/{id}', 'Url\UrlDataApiController@fetchUrls');

当我点击这个 api 时

http://localhost:8000/api/url-data/{1}

响应看起来像

{
    "urlData": [
       {
           "id": 1,
           "url" "https://example1.com/file"
       },
       {
           "id": 1,
           "url": "https://example2.com/file"
       }
    ]
 }

有什么方法可以代替获得响应,我们可以使用迭代从 url 下载文件吗?或重定向到响应中的网址?

【问题讨论】:

  • 你的 Laravel 版本是多少?
  • 我刚才已经提到了。错字。

标签: php laravel download


【解决方案1】:

你可以使用 Laravel 下载响应。

https://laravel.com/docs/8.x/responses#file-downloads

$headers = [
          'Content-Type' => 'application/pdf',
       ];
return response()->download($file, 'filename.pdf', $headers);

基于 Laravel 版本,也许你应该使用:

$file= public_path(). "/download/info.pdf";

$headers = array(
          'Content-Type: application/pdf',
        );

return Response::download($file, 'filename.pdf', $headers);

【讨论】:

  • 我可以知道如何通过遍历响应中的所有 url 来做到这一点吗?
  • 你的意思是文件应该反复下载吗?
  • 是的。无论$urlData 中的网址是什么,都应该下载它们。更要提的是,我问的是替代方案,而不是返回 json 响应。如果我删除它,$urlData 将包含基本上是一个集合的数据。
  • 这个怎么样:return response()->download([public_path('myimage.jpg'),public_path('myimage2.jpg')]);
  • 当我检查类似的例子时,他们使用了 zip 文件。有人提到,这是不可能的stackoverflow.com/questions/36675505/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2016-07-23
相关资源
最近更新 更多