php - 带有 Content-Disposition : attachment 的 PHP 中的文件下载问题

标签 php zend-framework download attachment content-disposition

我的网页上有一个链接,用于下载我在服务器上生成的 .CSV 文件。下载代码如下:

//open/save dialog box
header('Content-Disposition: attachment; filename="inventoryData.csv"');
//content type
header('Content-type: application/excel');
//read from server and write to buffer
readfile('spreadsheet/inventory.csv');

当我打开服务器上的文件时,它看起来很好。但是,当我通过对话框下载文件时,它会将网页的 HTML 代码添加到 .csv 文件中。

知道为什么会这样吗?

最佳答案

如果此代码位于 Controller 操作中,我认为这是因为您使用的是 ZF,那么您需要禁用布局和 View 渲染器,因为它将尝试渲染 View 。

尝试:

public function downloadAction()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);

    //...

    //open/save dialog box
    header('Content-Disposition: attachment; filename="inventoryData.csv"');
    //content type
    header('Content-type: application/excel');
    //read from server and write to buffer
    readfile('spreadsheet/inventory.csv');
}

$this->_helper->layout()->disableLayout(); 阻止渲染你的布局脚本(假设你使用布局),并且 $this->_helper->viewRenderer->setNoRender(true); 告诉 View 渲染器不要渲染可能包含一些 HTML 或空格的 Controller 操作的 View 脚本。

关于php - 带有 Content-Disposition : attachment 的 PHP 中的文件下载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10946077/

相关文章:

php - 为什么分页不起作用并在 wordpress 网站上出现 404 错误?

zend-framework - zend框架和Google Analytics(分析)数据

php - 如何使用按钮下载 HTML 格式的图像

php - 如何列出自关系表?

php - 撇号 (') 转换为 �

zend-framework - 如果验证失败,为什么不在 zend_form 上显示错误消息?

vb6 - 下载文件 - VB6

file - Cordova - 下载下载文件夹中的文件

php - PHP包含相对路径

php - 未捕获的异常 'Zend_Log_Exception' 消息文件。无法使用模式 "a"打开日志