noo*_*php 17 force-download zend-framework2
我正在尝试使用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\""));
}
Run Code Online (Sandbox Code Playgroud)
现在我收到了这个错误
/var/www/whowantsmymoney/vendor/zendframework/zendframework/library/Zend/Http/Request.php:88
Run Code Online (Sandbox Code Playgroud)
信息:
A valid request line was not found in the provided string
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
#0 /var/www/whowantsmymoney/module/Admin/src/Admin/Controller/LanguageController.php(93): Zend\Http\Request::fromString('Content-Type: a...')
Run Code Online (Sandbox Code Playgroud)
Ayd*_*san 36
此代码可以帮助您进行简单的文件下载.
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;
}
Run Code Online (Sandbox Code Playgroud)
我想这段代码有很多不足之处,但应该在简单的情况下工作,就像我的一样.我不知道你怎么处理块中的文件.也许其他人可以解决一些问题?
编辑 - 发送流
我在这里添加了这个用于提供信息的目的.它可能是强制下载的更好方法,因为它将使用更少的内存.
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;
Run Code Online (Sandbox Code Playgroud)
感谢@Aydin Hassan的回复,但他的回答中缺少几个重要的标题.小心一点.
完整标头堆栈:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11767 次 |
| 最近记录: |