如何强制用户下载(另存为对话框)刚刚生成的文件?

I'm generating a file using the query

SELECT * INTO OUTFILE " . "'c:/myfile.csv'" . " FIELDS TERMINATED BY ','  LINES TERMINATED BY '
' FROM sample

My file is now in C:/myfile.csv. I want the user to download the file. How can I achieve this?

You could :

  • Send an HTTP header, to indicate the kind of data you're sending, and that it should be downloaded to a file.
  • And, then, send the content of that file.


In PHP, something like this should do the trick :

header('Content-Disposition: attachment; filename="my-file.csv"');  // The name which will be suggested to the user
readfile('c:/myfile.csv');  // outputs the content of the file

You need to set Content-disposition: attachment in the header. In php, use header function to achieve this.

if(!$fdl=@fopen($fileString,'r')){
die("Cannot Open File!");
} else {
 header("Cache-Control: ");// leave blank to avoid IE errors
 header("Pragma: ");// leave blank to avoid IE errors
 header("Content-type: text/csv");
 header("Content-Disposition: attachment; filename=\"".$fileName."\"");
 header("Content-length:".(string)(filesize($fileString)));
sleep(1);
fpassthru($fdl);
}