php - Zend 框架 CSV 下载
问题描述
我目前正在 Zend Framwork 中开发 CSV 生成器。此时我可以在服务器端创建一个有效的 CSV 文件,现在我想下载该文件。我目前正在使用以下代码:
$reader = new \PHPExcel_Reader_CSV();
$reader->setReadDataOnly(true);
$excel = $reader->load($file); //$file = Path of the csv file in the local storage
$writer = \PHPExcel_IOFactory::createWriter($excel, 'CSV');
$path = 'public/download';
$fileName = 'test.csv';
$writer->save($path . '/' . $fileName);
$response = new ResponseStream();
$response->setStream(fopen($path . '/' . $fileName, 'r'));
$headers = new Headers();
$headers->addHeaders([
'Content-Type' => [
'application/force-download',
'application/octet-stream',
'application/download'
],
'Content-Length' => filesize($path . '/' . $fileName),
'Content-Disposition' => 'attachment;filename=' . $fileName,
'Cache-Control' => 'must-revalidate',
'Pragma' => 'no-cache',
'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT'
]);
$response->setHeaders($headers);
$cookie = new SetCookie('downloadComplete', 'true', time() + 60 * 60, '/');
$response->getHeaders()->addHeader($cookie);
$response->setContent($writer);
return $response;
现在的问题是我只得到一个 Zend 错误弹出窗口:
statusCode 200 thrownError SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 21 of the JSON data
以及我的 CSV 内容作为响应文本。
你有想法吗?提前致谢。
解决方案
经过大量调查后,我发现只有当我们通过 zend 向下载操作发送 Post 请求时,下载才会失败(我假设它会覆盖自设置的标头)。因此,我通过 java 脚本重定向($viewModel->addScriptBlock('window.location = "Your URL";');
)发送了请求并且它起作用了。
推荐阅读
- c++ - 在 C++ 中使用 sort() 函数对字符串数组进行排序的最坏情况时间复杂度是多少?
- ssas - 我们可以将两种措施合二为一吗?
- c# - 多层感知器(神经网络) - 我错过了什么?
- java - for循环中的多个数组
- php - Codeigniter 3 博客应用程序:重定向到更新的帖子失败
- python - 创建与每一行具有相同列表的新熊猫列?
- image - JMeter - 从数据文件中读取图像以进行 PUT 请求
- ethereum - Nethereum 异常:“在 JSON 中找不到必需的属性‘代码’。”
- nsis - NSIS反模拟器
- r - 如何使用ggplot在R中沿x轴填充缺失的时间戳值?