I'm having some problems generating a file download response in Laravel 5.1 while trying to download a file from Amazon S3.
This is my controller action:
/**
* @param GetRequest $request
* @return \Symfony\Component\HttpFoundation\Response
*/
public function get(GetRequest $request)
{
$fileEntry = $this->fileRepository->find();
$file = Storage::disk('s3')->get('projects/'.$fileEntry->project.'/'.$fileEntry->name);
return $this->respondDownload($file, $fileEntry->name, $fileEntry->type);
}
And this is the respondDownload
method:
/**
* Respond with a file download.
*
* @param $fileContent
* @param $fileName
* @param $mime
* @return \Symfony\Component\HttpFoundation\Response
*/
public function respondDownload($fileContent, $fileName, $mime)
{
return (new Response($fileContent, 200))
->header('Content-Type', $mime)
->header('Content-Disposition', 'attachment; filename="'.$fileName.'"');
}
If I open the developer tools I can see that the response is successful and the content is set to the file content, but the browser is not prompting to save the file somewhere.
How can I solve this problem? Is something wrong with the headers?
Edit
I also tried making a streamed response but the browser is still not showing a save file modal.
public function respondDownload($fileContent, $fileName, $mime)
{
return (new StreamedResponse(function() use ($fileContent)
{
echo $fileContent;
}, 200, [
'Content-Type' => $mime,
'Content-Disposition' => 'attachment; filename="'.$fileName.'"'
]));
}
Edit 2
The actual problem was caused by how I sent the download request to the server.
Previously I was making an AJAX request to the server and that wasn't making the browser to prompt me where to save the downloaded file.
In order to fix that I simply had to start the download request from an a
tag.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments