【问题标题】:How to force the user to download (Save as dialog) the file which just generated?如何强制用户下载(另存为对话框)刚刚生成的文件?
【发布时间】:2023-03-11 06:29:01
【问题描述】:
我正在使用查询生成文件
SELECT * INTO OUTFILE " . "'c:/myfile.csv'" . " FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' FROM sample
我的文件现在位于 C:/myfile.csv 中。我希望用户下载文件。我怎样才能做到这一点?
【问题讨论】:
标签:
php
mysql
sql
into-outfile
【解决方案1】:
你可以:
- 发送一个 HTTP 标头,以指明您要发送的数据类型,以及应将其下载到文件中。
- 然后,发送该文件的内容。
在 PHP 中,这样的事情应该可以解决问题:
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
【解决方案2】:
您需要在标题中设置Content-disposition: attachment。在php中,使用header函数来实现。
【解决方案3】:
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);
}