Skip to content
Advertisement

how to set header in laravel before firing a download

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.

Advertisement

Answer

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',
            ]);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement