【发布时间】: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-disposition值attachment;