我正在寻找一种方法来强制浏览器下载图像而不是只显示它.
我已经看了很多(并且深入),似乎没有标准的方法来正确地做到这一点.
Facebook的方式,它是一些PHP,我猜他们在最后放了一个参数: ?dl = 1
所以它肯定是一个PHP页面背后我猜的网址重写
<a class="itemAnchor" role="menuitem" tabindex="-1" href="http://a5.sphotos.ak.fbcdn.net/hphotos-ak-ash4/327910_2733459209258_1040639162_2895571_6924037615_o.jpg?dl=1" rel="ignore"><span class="itemLabel fsm">Download</span></a>
Run Code Online (Sandbox Code Playgroud)
所以,如果你有任何线索他们是如何做到的...我的线索是他们可能在PHP页面的标题中做了一些事情
他们只是像使用任何其他文件一样强制下载使用HTTP标头:
<?php
$file = 'C:\\test.jpg';
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Type: '.mime_content_type($file));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file));
readfile($file);
?>
Run Code Online (Sandbox Code Playgroud)
X-SENDFILE
对于较大的文件或繁忙的Web服务器,我建议使用X-SendFile头而不是使用readfile()函数(请注意,您需要mod_xsendfile在Apache中安装).
header('X-Sendfile: '.$file);
//readfile($file);
Run Code Online (Sandbox Code Playgroud)
.htccess
正如您所注意到的,Facebook URL指向jpg文件,而不是PHP文件.您需要在.htaccess文件中进行URL重写才能执行此操作.
类似下面的东西应该工作(注意你需要使用真实的URL,检查内容$_SERVER).
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Run Code Online (Sandbox Code Playgroud)