readfile下载空文件和错误的文件类型

时间:2015-04-21 09:46:21

标签: php jquery csv

我使用下面的代码从按钮单击下载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";
}

的download.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个文件。

4 个答案:

答案 0 :(得分:0)

尝试

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

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

答案 1 :(得分:0)

以下代码使用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 ();

答案 2 :(得分:0)

您可以使用您想要的文件名简单地修改脚本位置:

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

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

有了这个,你可以摆脱你的.htaccess黑客,并将PHP代码减少到:

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

答案 3 :(得分:-2)

我认为当您尝试下载同一文件的两个副本时,它们会相互抵消