aristotle11
aristotle11

Reputation: 54

download files from url in php laravel

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?

Upvotes: 0

Views: 3743

Answers (2)

Nageen
Nageen

Reputation: 1765

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

Upvotes: 0

mehri abbasi
mehri abbasi

Reputation: 155

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

Upvotes: 1

Related Questions