我做了一個表格,使用Zend\Filter\File\RenameUpload
過濾器將文件上傳到文件夾./data/uploads
。Zend Framework 2文件下載
這工作就像一個魅力。我現在的問題是如何提供這個文件給用戶下載它?
我認爲這將是這樣的:
$response->setContent(file_get_contents('./data/uploads/file.png'));
但我想知道什麼是做到這一點的最好辦法。
我做了一個表格,使用Zend\Filter\File\RenameUpload
過濾器將文件上傳到文件夾./data/uploads
。Zend Framework 2文件下載
這工作就像一個魅力。我現在的問題是如何提供這個文件給用戶下載它?
我認爲這將是這樣的:
$response->setContent(file_get_contents('./data/uploads/file.png'));
但我想知道什麼是做到這一點的最好辦法。
感謝@henrik的響應,但有幾個重要的頭在他的回答失蹤。小心一點。
完整標頭堆棧:
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;
}
的
對於任何遇到此線程尋找答案的人來說,這是一個可行的解決方案,它正在使用流!
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;
}
這裏找到: force download using zf2
更多細節在這裏: sending stream responses with zend
可能重複的[使用力下載ZF2](http://stackoverflow.com/questions/15219873/force-download-using-zf2) – Makoto