Rol*_*and 62 php http download
我的服务器上有一个CSV文件.如果用户点击了应该下载的链接,而是在我的浏览器窗口中打开它.
我的代码如下所示
<a href="files/csv/example/example.csv">
Click here to download an example of the "CSV" file
</a>
Run Code Online (Sandbox Code Playgroud)
这是一个普通的网络服务器,我可以完成所有的开发工作.
我尝试过类似的东西:
<a href="files/csv/example/csv.php">
Click here to download an example of the "CSV" file
</a>
Run Code Online (Sandbox Code Playgroud)
现在我的csv.php
文件的内容:
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
Run Code Online (Sandbox Code Playgroud)
现在我的问题是它正在下载,但不是我的CSV文件.它会创建一个新文件.
rob*_*lls 104
要强制下载服务器上的所有CSV文件,请添加.htaccess文件:
AddType application/octet-stream csv
Run Code Online (Sandbox Code Playgroud)
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");
Run Code Online (Sandbox Code Playgroud)
Ata*_*CSE 23
或者您可以使用HTML5执行此操作.简单地说
<a href="example.csv" download>download not open it</a>
Run Code Online (Sandbox Code Playgroud)
Mic*_*rdt 15
这不能可靠地完成,因为由浏览器决定如何处理它被要求检索的URL.
您可以通过发送Content-disposition标头向浏览器建议它应该立即提供"保存到磁盘":
header("Content-disposition: attachment");
Run Code Online (Sandbox Code Playgroud)
我不确定各种浏览器是否支持这种情况.另一种方法是发送一个Content-type的application/octet-stream,但这是一个hack(你基本上是告诉浏览器"我不是在告诉你这是什么类型的文件"而且取决于大多数事实然后,浏览器将提供下载对话框)并据称导致Internet Explorer出现问题.
在Web Authoring FAQ中阅读更多相关信息.
编辑您已经切换到PHP文件来传递数据 - 这是设置Content-disposition标头所必需的(除非有一些神秘的Apache设置也可以执行此操作).现在剩下要做的就是让PHP文件读取CSV文件的内容并打印它们 - filename=example.csv
标题中只向客户端浏览器建议用于文件的名称,它实际上并不是从文件中获取数据服务器上的文件.
Fra*_*anz 13
这是一个更安全的浏览器解决方案:
$fp = @fopen($yourfile, 'rb');
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
header('Content-Type: "application/octet-stream"');
header('Content-Disposition: attachment; filename="yourname.file"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".filesize($yourfile));
}
else
{
header('Content-Type: "application/octet-stream"');
header('Content-Disposition: attachment; filename="yourname.file"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".filesize($yourfile));
}
fpassthru($fp);
fclose($fp);
Run Code Online (Sandbox Code Playgroud)