使用浏览器提示下载文件 [英] using the browser prompt to download a file
问题描述
我在我试图下载一个逗号分隔的文件(CSV),一个PHP / MySQL的网站。我创建CSV文件包含逗号分隔的数据(姓名,地址,城市,州)。我创建CSV文件确定,并将其放置在网站的/下载目录。到现在为止还挺好。我一直在寻找上线和code触发浏览器的下载提示,我看到最多的往往是:
I have a php/mysql site in which I am trying to download a comma delimited file (CSV). The csv file I create contains comma delimited data (name, address, city, state). I create the csv file ok and place it in the site's /downloads directory. So far so good. I have been looking on line and the code to trigger the browser's download prompt that I see the most often is:
$path = $_SERVER['DOCUMENT_ROOT'];
$exportfile = "emailclientaddresses.csv";
$fullpath = "downloads/" . $exportfile;
header("Content-type: text/plain");
header("Content-Length: ".filesize($exportfile));
header("Content-Disposition: attachment; filename=" . $fullpath);
该$导出文件是我的code创建的CSV文件。没关系。这样做是:
The $exportfile is the csv file that my code created. It's ok. What this does is:
- 的$完整路径显示在浏览器下载提示在一个非常奇怪的格式:download_emailclientaddresses.csv
- 当它的下载,当前网页下载或CSV文件,当前网页的组合。
OK,我已经尝试了很多东西,并没有奏效。所以,如果有人可以帮助我,我将AP preciate它。谢谢你。
OK, I have tried a lot of things and nothing has worked. So, if anyone can help me I would appreciate it. Thank you.
ED科恩
推荐答案
借助 PHP文档提供很好的例子:
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
修改 (响应发表评论,解释)的
header('Content-Description: File Transfer');
不要在浏览器中显示,但传输文件。
Do not display in the browser, but transfer the file.
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
文件是一个二进制文件。结果
浏览器通常下载二进制文件,除非它们可以显示它们。
File is a binary file.
Browsers generally download binary files, unless they can display them.
header('Content-Disposition: attachment; filename='.basename($file));
请下载对话框显示正确的文件名。结果
注意:您可以使用任何文件名
Make the download dialog show the proper file name.
Note: You can use any file name.
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
文件不应被浏览器高速缓存。结果
缓存可在动态内容的情况下会引起麻烦。
File should not be cached by the browser.
Cache could cause trouble in case of dynamic content.
header('Content-Length: ' . filesize($file));
发送正确的文件大小设置为浏览器,搜索
否则浏览器是无法估计的转移时间。
Send the correct file size to the browser,
otherwise the browser is unable to estimate the transfer-time.
ob_clean();
flush();
确认头下载开始之前发送给浏览器。
Make sure the headers are send to the browser before the download starts.
readfile($file);
文件发送到浏览器。
Send the file to the browser.
exit;
完成:)
这篇关于使用浏览器提示下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!