【问题标题】:readfile downloads an empty file and wrong file typereadfile 下载一个空文件和错误的文件类型
【发布时间】:2015-06-28 09:36:36
【问题描述】:

我正在使用下面的代码通过单击按钮下载 csv 文件。

JS

$(document).on("click", "#CSV", function () {

    var csv_value = $('#result').table2CSV({
        delivery: 'value'
    });
    console.log(csv_value);
    $.ajax({
        type: "POST",
        url: "csv.php",
        data: {
            csv: csv_value
        },
        success: function (html) {
             window.location.href = "download.php";
        }
    });

});

csv.php

require_once ("session_start.php");
if (isset ( $_POST ['csv'] )) {
$file = $_POST['csv'];
$_SESSION ['csvf'] = $file; 
} else {
    echo "No CSV Data";
}

下载.php:

session_start();
    $file =$_SESSION['csvf'];
    $filename = $file."_".date("Y-m-d_H-i",time());
    header ( "Content-type: application/vnd.ms-excel" );
    header ( "Content-disposition: filename=" . $filename . ".csv" );
    readfile($filename);
    exit ();

当我执行该函数时,尽管传递了正确的标头(通过控制台确认),但下载的文件是 download.php,该文件也是空的。此外,当我使用print() 时,它会打印CSV 数据,因此我知道该文件不是空的,但它还会生成一个.php 文件并打印其中的所有内容,包括标题。我该如何解决这个问题?

编辑

我尝试在.htaccess 中使用以下代码强制下载,但无济于事。

<FilesMatch "\.(?i:csv)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

结果仍然是download.php 文件。

【问题讨论】:

  • 提示:在readfile()之前停止会话。
  • header ( "Content-disposition: filename=" . $filename . ".csv" ); 缺失 Content-dispositionattachment;

标签: php jquery csv


【解决方案1】:

我认为这发生在您尝试下载同一文件的两个副本时,他们将相互取消

【讨论】:

  • 你在说什么文件?
【解决方案2】:

下面的代码使用print()而不是readfile()对我有用

session_start ();
$file = $_SESSION ['csvf'];
$_table = $_SESSION['table']; //table Name
$filename =$_table."_".date ( "Y-m-d_H-i", time () ).".csv";  
header ( "Content-type: text/csv" );
header ( "Content-Disposition: attachment; filename=".$filename );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ( $file ) );
print ($file) ;
exit ();

【讨论】:

    【解决方案3】:

    你可以简单地用你想要的文件名后缀脚本位置:

    success: function (html) {
         window.location.href = "download.php/something.csv";
    }
    

    它仍将运行download.php,但浏览器只会看到 URL 的最后部分,并按照您的预期处理下载。

    有了这个,你也可以摆脱你的.htaccess hack,并将 php 代码减少到:

    session_start();
    $file =$_SESSION['csvf'];
    session_write_close();
    readfile($file);
    

    【讨论】:

      【解决方案4】:

      试试

      Content-Disposition: attachment; filename="<your file name>".
      

      您有 2 个 Content-disposition 标头(第一个将被覆盖)。

      【讨论】:

      • 我只是尝试使用它作为标题,但它也不起作用。
      猜你喜欢
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      相关资源
      最近更新 更多