php - 使用 zenframework 3 下载文件
问题描述
我在任何地方都找不到答案,甚至在这里也找不到,所以这是我的问题。
在这个 hello 示例中,控制器下载文件:
class DownloadController extends AbstractActionController
{
/**
* This is the default "index" action of the controller. It displays the
* Downloads page.
*/
public function indexAction()
{
return new ViewModel();
}
/**
* This is the 'file' action that is invoked
* when a user wants to download the given file.
*/
public function fileAction()
{
// Get the file name from GET variable
$fileName = $this->params()->fromQuery('name', '');
// Take some precautions to make file name secure
$fileName = str_replace("/", "", $fileName); // Remove slashes
$fileName = str_replace("\\", "", $fileName); // Remove back-slashes
// Try to open file
$path = './data/download/' . $fileName;
if (!is_readable($path)) {
// Set 404 Not Found status code
$this->getResponse()->setStatusCode(404);
return;
}
// Get file size in bytes
$fileSize = filesize($path);
// Write HTTP headers
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine(
"Content-type: application/octet-stream");
$headers->addHeaderLine(
"Content-Disposition: attachment; filename=\"" .
$fileName . "\"");
$headers->addHeaderLine("Content-length: $fileSize");
$headers->addHeaderLine("Cache-control: private");
// Write file content
$fileContent = file_get_contents($path);
if($fileContent!=false) {
$response->setContent($fileContent);
} else {
// Set 500 Server Error status code
$this->getResponse()->setStatusCode(500);
return;
}
// Return Response to avoid default view rendering
return $this->getResponse();
}
}
在 Apache2 网络服务器中运行它时出现此错误:
A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
Application\Controller\DownloadController
No Exception available
但是在使用 PHP 内置服务器时它工作正常:
php -S 0.0.0.0:8081 -t helloworld public/index.php
我在这里做错了什么?
解决方案
我猜你应该返回 $response 而不是 $this->getResponse()。我将展示我用于下载文件的工作代码:
public function downloadAction()
{
$file = 'file content...';
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Content-Type', 'text/csv')
->addHeaderLine('Content-Disposition', "attachment; filename=filename.csv")
->addHeaderLine("Pragma: no-cache")
->addHeaderLine("Content-Transfer-Encoding: UTF-8");
$response->setContent($file);
return $response;
}
推荐阅读
- git - 在 Eclipse Git 中找不到“添加到索引”选项
- java - 如何将 fileStream 转换为 blob 以将其添加到 sql 表中?
- c++ - 在 lambda 中使用仿函数
- python - 在 Pandas 中,如何根据 groupby 标准获取多个子集数据框?
- java - 需要帮助在字符串问题中替换名称(clojure)
- android - Android,layoutParams 是否指向父视图而不是视图本身?
- sftp - 如何使用 Deno 读取/写入 sftp 服务器
- python - Spacy EntityRuler 没有使用正则表达式模式给出正确的结果
- c++ - 我正在尝试解决 spoj 中的下一个回文问题,但不知道为什么会收到 SIGABRT 错误
- xml - xslt 如果不为空,则将元素值复制到可能不存在的新元素