我应该设置一个简单的下载管理器 我不明白这段代码不起作用:
protected function doDownload($filename){
//$this->_helper->layout()->disableLayout();
//$this->_helper->viewRenderer->setNoRender(true);
$dir = Zend_Registry::get('dir');
$file = $dir->assets.$filename;
if(file_exists($file)){
$response = $this->getResponse();
$response->setHeader('Content-Description','File Transfer', true);
$response->setHeader('Content-Type','application/octet-stream', true);
$response->setHeader('Content-Disposition','attachment; filename='.basename($file), true);
$response->setHeader('Content-Transfer-Encoding','binary', true);
$response->setHeader('Expires','0', true);
$response->setHeader('Cache-Control','must-revalidate, post-check=0, pre-check=0', true);
$response->setHeader('Pragma','public', true);
$response->setHeader('Content-Length: ' , filesize($file),true);
ob_clean();
flush();
readfile($file);
exit(0);
/*header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit(0);*/
}
}
使用注释代码时脚本运行正常。
答案 0 :(得分:5)
您基本上不通过Zend Framework执行任何输出(除了标题)。请尝试以下方法:
if (file_exists($file)) {
$this->getResponse()
->setHeader('Content-Description','File Transfer', true)
->setHeader('Content-Type','application/octet-stream', true)
->setHeader('Content-Disposition','attachment; filename='.basename($file), true)
->setHeader('Content-Transfer-Encoding','binary', true)
->setHeader('Expires','0', true)
->setHeader('Cache-Control','must-revalidate, post-check=0, pre-check=0', true)
->setHeader('Pragma','public', true)
->setHeader('Content-Length: ' , filesize($file),true);
$this->getResponse()->setBody(file_get_contents($file));
}
BTW你必须再次注释掉你的前两行代码并且不要退出(0),否则它将无法工作,因为标题和正文的实际发送将在动作后完成。 / p>
答案 1 :(得分:0)
就个人而言,我不明白为什么你的代码应该有效? readfile()是否会在输出文件内容之前自动触发$ response对象上的sendHeaders()或writeHeaders()方法?!?我认为你应该调用这个方法或使用一种方法来调用它...就像在另一个答案中建议的$ this-> getResponse-> setBody()