Laravel Content-Length header can't be sent with file response

Viewed 45

I'm actually trying to send the Content-Length header with my file response (for downloading status bar purproses on client side) using this method :

return response()->header('Content-Length', $fileSize)->file($this->filesPath.$fileName);

But i'm getting an error :

BadMethodCallException: Method Illuminate\Routing\ResponseFactory::header does not exist. in file /www/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php on line 113

It seems that the method is not recognized when there is "file()" in the response.

Here are my response headers :

My headers

Note : Apache webserver based on Linux machine running Laravel 8 with PHP 8.1

Aditional informations :

After testing on different environements and with multiples files, i've found out that the Content-Length header is working only with images. I've tested it in Laravel 9 & 8 and still can't send Content-Length header manually. Any other header is working.

1 Answers

Use the pre-built download() method to send headers

$filesPath = 'path/to/file'; // change this
$fileName = 'file-name'; // change this
$fileSize = 'size'; // change this

$headers = [
    'Content-Length' => $fileSize
];

return response()->download($filesPath, $fileName, $headers);
Related