问题描述
我希望用户能够下载我的服务器上的一些文件,但是当我尝试使用互联网上的许多此类示例中的任何一个时,似乎没有什么对我有用.我试过这样的代码:
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"'
但是没有显示保存对话框.
But the save dialog isn't displayed.
我也尝试在内容处置标题中使用内联而不是附件,但这也没有什么不同,我已经在 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:
- 使用 Jquery、PHP 下载 Ajax 文件
这篇关于使用 header() 强制使用 php 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!