Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set header in laravel before firing a download

Tags:

php

laravel

I want to set headers before firing a download.

Before I used to do something like this in plain php:

      header('Content-Description: File Transfer');
      header('Content-Type: application/pdf');
      header('Content-Disposition: attachment; filename="'.basename($path).'"');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($path));
      readfile($path);

Now I want to still be able to set the same headers and call the laravel download function and pass my headers, something like:

return response()->download($pathToFile, $name, $headers);

where the $headers variable should contain my header's. Anybody who has ever done this.

like image 244
Samuel Thomas Avatar asked Dec 18 '22 04:12

Samuel Thomas


2 Answers

As simple as this

$headers = [
    'Content-Description' => 'File Transfer',
    'Content-Type' => 'application/pdf',
];

return \Response::download($pathToFile, $name, $headers);
like image 100
Mo Kawsara Avatar answered Jan 04 '23 22:01

Mo Kawsara


From the docs

You may use the header method to add a series of headers to the response before sending it back to the user:

return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

return response($content)
            ->withHeaders([
                'Content-Type' => $type,
                'X-Header-One' => 'Header Value',
                'X-Header-Two' => 'Header Value',
            ]);
like image 27
Mr. Pyramid Avatar answered Jan 04 '23 21:01

Mr. Pyramid