[英]Download CSV file from server to local direcory
我编写了一个脚本,用于在其中创建CSV文件并将其保存在服务器的目录中。 CSV文件包含查询的属性。 使用Jquery和Ajax单击按钮即可执行整个过程。
我现在想做的是能够将生成的CSV保存在本地。 我发现了类似的问题,但没有找到有关如何创建对话框的提示,该对话框将提示客户端指定保存文件的位置。
这是我的Jquery代码的一部分:
var nodeId = 'something';
var ajaxurl = 'requestsII/exportNodeData.php', // script to run
data = {nodeId:nodeId}; // data to pass
$.post(ajaxurl, data, function (response) {
//alert(response);
});
这是我的PHP脚本:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv"); // EDITED
if ($db) {
$stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId');
$stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId));
#$results=$stmt->fetchAll(PDO::FETCH_OBJ);
#$json=json_encode($results);
#echo($json);
$filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv';
$data = fopen($filename, 'w');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($data, $row);
}
fclose($data);
}
echo($data); // EDITED
问题是如何在本地下载在PHP脚本中创建的CSV文件?
试试这个代码
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
编辑 :
试试这个代码
if ($db)
{
$stmt = $db->prepare('SELECT kodpop AS "ΚΩΔΙΚΟΣ ΚΟΜΒΟΥ",itemcode AS "ΚΩΔΙΚΟΣ ΕΞΟΠΛΙΣΜΟΥ",temaxia AS "ΤΕΜΑΧΙΑ",status AS "STATUS" FROM bom WHERE type IN (:typeI, :typeII) AND kodpop = :nodeId');
$stmt->execute(array('typeI' =>$typeI,'typeII' => $typeII,'nodeId' => $nodeId));
#$results=$stmt->fetchAll(PDO::FETCH_OBJ);
#$json=json_encode($results);
#echo($json);
$filename = '/var/www/dkar/ruralBroadband/ruralApp/rural/csvExports/'.$nodeId.'.csv';
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$filename);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
}
毕竟,我没有使用上面的方法,而是这样做了,它可以正常工作,并且更直接:
var ajaxurl = 'exportNodeData.php', // script to run
data = {nodeId:nodeId}; // data to pass
$.post(ajaxurl, data, function (response) {
document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';
});
这是ajax请求,我执行该命令是为了创建CSV文件(该文件也已压缩)。 然后,我使用此行:
document.location.href = 'https://www.ruralauditor.gr/csvExports/'+nodeId+'.zip';
为了强制下载文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.