为了账号安全,请及时绑定邮箱和手机立即绑定

使用header()强制文件下载

使用header()强制文件下载

PHP
慕的地10843 2019-07-30 16:52:32
使用header()强制文件下载我希望用户能够下载我服务器上的一些文件,但是当我尝试使用互联网上的任何一个这样的例子时,似乎没有什么对我有用。我尝试过这样的代码:<?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");我甚至试图使用我能找到的最基本的例子,如下所示:<?phpheader('Content-type: image/png');header('Content-Disposition: attachment; filename="Image.png"');readfile('Image.png');当我测试了这个时,我已经删除了所有其他代码,并使用了一个空文件,仅使用此代码来删除外部源创建的任何错误。当我在控制台中查看时,文件会以正确的标题发送,即'Content-Disposition: attachment; filename="Image.png"'但是不显示保存对话框。我也尝试使用inline而不是内容处理标题中的附件,但这也没有什么区别,我已经在Firefox 8.0.1 Chrome 15.0.874.121和Safari 5.1.1中测试过了。
查看完整描述

3 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

我很确定你没有在文件下载中添加mime类型作为JPEG:


header('Content-Type: image/png');

这些标题从未让我失望:


$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));

$size   = filesize($file);


header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

header('Content-Disposition: attachment; filename=' . $quoted); 

header('Content-Transfer-Encoding: binary');

header('Connection: Keep-Alive');

header('Expires: 0');

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Pragma: public');

header('Content-Length: ' . $size);


查看完整回答
反对 回复 2019-07-30
?
皈依舞

TA贡献1851条经验 获得超3个赞


这对我来说就像下载PNG和PDF的魅力一样。


header('Content-Description: File Transfer');

header('Content-Type: application/octet-stream');

header('Content-Disposition: attachment; filename="'.$file_name.'"');

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: ' . filesize($file_url)); //Absolute URL

ob_clean();

flush();

readfile($file_url); //Absolute URL

exit();


查看完整回答
反对 回复 2019-07-30
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

问题是我使用ajax将消息发布到服务器,当我使用直接链接下载文件时一切正常。

我使用了其他Stackoverflow Q&A材料,它对我来说很有用:


查看完整回答
反对 回复 2019-07-30
  • 3 回答
  • 0 关注
  • 726 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信