Returning file response from an external API call in Laravel

Viewed 29

I have this method in my controller where I'm calling an external URL that returns a PDF file:

public function get()
{
    $response = Http::withHeaders(['Content-Type' => 'application/pdf'])
      ->get('https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf')
      ->body();

    return $response;
}

routes/api.php:

Route::get('/file', [FileController::class, 'get']);

Calling that route in the browser displays this gibberish output instead of the actual file: enter image description here

If I do return response()->file($file), it's throwing an error:

Symfony \ Component\ HttpFoundation\ File \ Exception\ FileNotFoundException

Is there any way to achieve it without having to store the file first?

1 Answers

To send a file response without storing the file locally you an use streamDownload:

return response()->streamDownload(function () {
    echo Http::withHeaders(['Content-Type' => 'application/pdf'])
      ->get('https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf')
      ->body();
}, 'c4611_sample_explain.pdf');
Related