![](/img/trans.png)
[英]Using AsyncTask to download file from PHP site without any Open/Save dialog box
[英]How to download a specific CSV file from the server to the client using Save As dialog box in php?
我在服務器上有一個名為CO2.csv的文件,我希望用戶通過表單中的按鈕下載並使用新文件名將其保存到他的硬盤驅動器中的任何位置。
這是調用php代碼的按鈕的HTML腳本
<form action="FCO2.php" method="post" <?php if(empty($_SESSION["CO2"])){?>style="display:none"<?php } ?> >
<input type="submit" value="Export to CSV" name="submit">
</form>
這是FCO2.php
<?php
$file = 'temp/CO2temp.csv';
if(!$file)
{ // file does not exist
die('file not found');
}
else
{
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: text/csv");
header("Content-Transfer-Encoding: text/csv");
}
?>
但是它沒有用,它總是創建一個空文件,並且從不復制服務器上的文件。
哦,您只是錯過了對實際文件的調用,例如使用readfile
因此添加到:
<?php
$file = 'temp/CO2temp.csv';
if(!$file)
{ // file does not exist
die('file not found');
}
else
{
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: text/csv");
header("Content-Transfer-Encoding: text/csv");
readfile($file);
exit;// good practice but if this is the whole file, its not needed
}
?>
您正在輸出一堆標題,但是PHP在輸出文件之前結束。
您可以使用readfile來做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.