PHP 中的文件下载问题与内容处置:附件


File download issue in PHP with Content-Disposition: attachment

我的网页上有一个链接,可以下载.我在服务器上生成的 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文件中。

知道为什么会这样吗?

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

尝试:

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);告诉视图呈现器不要为可能包含一些 HTML 或空格的控制器操作呈现视图脚本。

这应该可以解决问题

  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Cache-Control: private",false);
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename='"inventoryData.csv'";" );
  header("Content-Transfer-Encoding: binary");

试试这个:

header("Content-type: application/octet-stream");
header("Content-disposition:attachment; filename=inventoryData.csv");