我正在使用下面的代码通过单击按钮下载 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
,尽管传递了正确的 header (通过控制台确认),文件也是空的。此外,当我使用 print()
时,它会打印 CSV
数据,因此我知道该文件不为空,但它还会生成一个 .php
文件并打印其中的所有内容,包括标题。我该如何解决这个问题?
编辑
我尝试使用 .htaccess
中的以下代码强制下载,但无济于事。
<FilesMatch "\.(?i:csv)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
结果还是一个download.php
文件。
最佳答案
尝试
Content-Disposition: attachment; filename="<your file name>".
并且您有 2 个 Content-disposition header (第一个将被覆盖)。
关于php - readfile 下载空文件和错误的文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29768586/