使用header()强制文件下载 [英] Force file download with php using header()
问题描述
我希望用户能够下载我服务器上的一些文件,但是当我尝试在互联网上使用这些中的任何一个例子时似乎对我没什么用。我尝试过这样的代码:
I want the user to be able to download some files I have on my server, but when I try to use any of the many examples of this around the internet nothing seems to work for me. I've tried code like this:
<?php
$size = filesize("Image.png");
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
readfile("Image.png");
我甚至试图使用我能找到的最基本的例子,如:
I've even tried to use the most basic example I could find, like this:
<?php
header('Content-type: image/png');
header('Content-Disposition: attachment; filename="Image.png"');
readfile('Image.png');
当我测试了这个时,我删除了所有其他代码并使用了一个空文件只是这段代码可以删除外部资源造成的任何错误。
When I've tested this I have removed all the other code I have and used an empty file with just this code to remove any faults created by external sources.
当我在控制台中查看时,文件会以正确的标题发送,即
When I look in the console the file gets sent with the right headers i.e
'Content-Disposition: attachment; filename="Image.png"'
但不显示保存对话框。
我也尝试在内容处置标题中使用内联而不是附件,但这也没有任何区别,我在Firefox 8.0.1 Chrome 15.0.874.121中测试了这一点和Safari 5.1.1。
I've also tried with inline instead of attachment in the content disposition header but that didn't make a difference either, I've tested this in Firefox 8.0.1 Chrome 15.0.874.121 and Safari 5.1.1.
推荐答案
问题是我使用ajax将消息发布到服务器,当我使用了直接链接下载文件一切正常。
The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.
我使用了这个其他Stackoverflow Q& A材料,它对我很有用:
I used this other Stackoverflow Q&A material instead, it worked great for me:
- Ajax File Download using Jquery, PHP
这篇关于使用header()强制文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!