0

I'm using php version 7.3 and laravel 5.4

I've a controller function fetchUrls which returns a json response containing urls data

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

Using this controller function in my routes

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

When I hit this api

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

The response looks like

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

Is there any way instead of getting response, can we download the file from url using iteration? or redirect to urls present in the response?

aristotle11
  • 54
  • 1
  • 10

2 Answers2

1

You can use Laravel download response.

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

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

base on Laravel version, maybe you should use:

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

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

return Response::download($file, 'filename.pdf', $headers);
mehri abbasi
  • 145
  • 1
  • 11
  • Can I know how I can do this by iterating through all urls from the response? – aristotle11 Sep 09 '21 at 14:12
  • Do you mean the files should be downloaded over and over again? – mehri abbasi Sep 09 '21 at 14:24
  • Yes. Whatever the urls in `$urlData`, they should get downloaded. And more thing to mention, I'm asking an alternative instead of return json response. If I remove it, `$urlData` will contain the data which is bascially a collection. – aristotle11 Sep 09 '21 at 14:26
  • How about this one: ```return response()->download([public_path('myimage.jpg'),public_path('myimage2.jpg')]);``` – mehri abbasi Sep 09 '21 at 14:34
  • As I checked similar examples, they used zip file. and someone mention that, it is not possible https://stackoverflow.com/questions/36675505/laravel-5-multiple-download-file – mehri abbasi Sep 09 '21 at 14:36
  • Appreciate you suggestions, I found another way to download the files, which I've modified in my frontend. – aristotle11 Sep 12 '21 at 13:36
0

You can use the below code to download the file from URL

return response()->streamDownload(function () {
                echo file_get_contents('https://www.pakainfo.com/wp-content/uploads/2021/09/image-url-for-testing.jpg');
            }, 'image-url-for-testing.jpg');

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

nageen nayak
  • 1,262
  • 2
  • 18
  • 28