Php 使用zenframework 3下载文件
我在任何地方都找不到答案,甚至在这里也找不到,所以这是我的问题 在此hello示例中,此控制器将下载文件:Php 使用zenframework 3下载文件,php,download,controller,zend-framework3,Php,Download,Controller,Zend Framework3,我在任何地方都找不到答案,甚至在这里也找不到,所以这是我的问题 在此hello示例中,此控制器将下载文件: class DownloadController extends AbstractActionController { /** * This is the default "index" action of the controller. It displays the * Downloads page. */ public function i
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 web服务器中运行时出现此错误:
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;
}
谢谢你的回答,但没有用。我得到这个错误:C:\Users\user~1\AppData\Local\Temp\S7k+Cocu.txt.part无法保存,因为无法读取源文件。请稍后再试,或者与服务器管理员联系。我刚刚将项目上载到CLOUD服务器,它可以在不修改代码的情况下工作。问题应该出在apache2服务器配置上。可能是htaccess文件?嗯。。是的,这可能是apache错误配置的问题。在这里检查我的答案如何配置ZF和apache vhost。htaccess应该是安装时的默认值。谢谢你,它正在工作。我刚刚在虚拟配置文件中添加了“订单允许、拒绝”和“全部允许”。我的链接对你有帮助吗?