我试图用ZF2做力下载。 下面是摘录到我的代码
use Zend\Http\Request;
.....
public function downloadAction() {
$response = new Request();
$response->setHeaders(Request::fromString("Content-Type: application/octet-stream\r\nContent-Length: 9\r\nContent-Disposition: attachment; filename=\"ultimate_remedy_readme.txt\""));
}
现在我得到这个错误
/var/www/whowantsmymoney/vendor/zendframework/zendframework/library/Zend/Http/Request.php:88
信息:
A valid request line was not found in the provided string
堆栈跟踪:
#0 /var/www/whowantsmymoney/module/Admin/src/Admin/Controller/LanguageController.php(93): Zend\Http\Request::fromString('Content-Type: a...')
此代码应帮助您为一个简单的文件下载。
public function downloadAction() {
$fileName = 'somefile';
if(!is_file($fileName)) {
//do something
}
$fileContents = file_get_contents($fileName);
$response = $this->getResponse();
$response->setContent($fileContents);
$headers = $response->getHeaders();
$headers->clearHeaders()
->addHeaderLine('Content-Type', 'whatever your content type is')
->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
->addHeaderLine('Content-Length', strlen($fileContents));
return $this->response;
}
我想这个代码极不理想很多,但应该在简单的情况下工作,因为是我的。 我不知道你会如何处理读取块的文件。 也许别人可以提供一些线索?
编辑-发送流
我已经为信息目的这里加入此。 这可能是更好的方式来强制下载,因为它会使用更少的内存。
public function downloadAction() {
$fileName = 'somefile';
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($fileName, 'r'));
$response->setStatusCode(200);
$headers = new \Zend\Http\Headers();
$headers->addHeaderLine('Content-Type', 'whatever your content type is')
->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
->addHeaderLine('Content-Length', filesize($fileName));
$response->setHeaders($headers);
return $response;
由于@Aydin哈桑的响应,但有几个重要的头在他的回答失踪。 请注意这一点。
全头堆栈:
public function downloadAction() {
$file = 'path/to/file';
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($file, 'r'));
$response->setStatusCode(200);
$response->setStreamName(basename($file));
$headers = new \Zend\Http\Headers();
$headers->addHeaders(array(
'Content-Disposition' => 'attachment; filename="' . basename($file) .'"',
'Content-Type' => 'application/octet-stream',
'Content-Length' => filesize($file),
'Expires' => '@0', // @0, because zf2 parses date as string to \DateTime() object
'Cache-Control' => 'must-revalidate',
'Pragma' => 'public'
));
$response->setHeaders($headers);
return $response;
}