I have a script that generates a file for download through ajax. I need to control this request because not everyone should be able to download a file. The process looks like this:
- Listen for click event, send ajax request with data to the server
- The request is handled, if everything is OK a temporary file is generated with the first line to be the filename and further content is the content of the file to download
- Send the URL for the newly generated file back to the ajax function and fill a hidden iframe's src attribute with that endpoint.
- When the endpoint is called, a controller method checks if the file exists, opens it and puts the first line to a
$filename
variable usingarray_shift
and puts the rest of the content to the$content
variable, - Set the headers for a download and echo out the
$content
variable.
Somehow this doesn't work as expected. It's not because of the iframe, because when I visit the URL in the browser Chrome tells me there an ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
error. I'm using Laravel and I don't see where I've set falsly headers?
The download script so far:
public function download($fileId)
{
$file = $this->tempFilesPath . $fileId;
if (file_exists($file)) {
$data = explode("\n", file_get_contents($file));
//@unlink($file);
$fileName = array_shift($data);
$content = implode("\n", $data);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename=' . $fileName);
echo $content;
exit;
}
}
Dumping the values of $fileName
and $content
shows the expected values.
Suggestions? Thanks.