1

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?

jstarnate
  • 319
  • 3
  • 15
  • Does this answer your question? [Laravel - display a PDF file in storage without forcing download?](https://stackoverflow.com/questions/25938294/laravel-display-a-pdf-file-in-storage-without-forcing-download) – STA Sep 15 '22 at 04:57
  • @sta Already tried it. Not working – jstarnate Sep 15 '22 at 09:26

1 Answers1

3

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');
apokryfos
  • 38,771
  • 9
  • 70
  • 114