如何可以强制在浏览器中的图像下载? [英] How can I force an Image download in the browser?
问题描述
我想强迫用户下载图像。在不打开浏览器。
<打击>可以使用HTML5这个属性下载
不过目前只有Chrome支持它。击>
我试过的.htaccess
解决方案,但它不能正常工作。
&LT;文件* .JPG&GT;
ForceType指令的应用程序/八位字节流
头中设置内容处置附件
&LT; /文件&GT;
我如何可以强制下载所有我的图片,如果链接的用户点击?
&LT; A HREF =http://blablabla.com/azerty/abc.jpg目标=_空白/&GT;下载&LT; / A&GT;
有两种方法可以做到这一点 - 之一,JS,一用PHP
在JS从本网站:
&LT; A HREF =JavaScript的:无效(0);
的onclick =document.execCommand('另存为',真正的'file.html');
&GT;保存该页面&LT; / A&GT;
在PHP中创建一个名为的download.php
的脚本,它类似于以下code:
&LT; PHP
//图像文件的强制下载指定的URL查询字符串并
//是在同一目录下的download.php脚本。
如果(空($ _ GET ['IMG'])){
标题(HTTP / 1.0 404未找到);
返回;
}
$基本名=基名($ _ GET ['IMG']);
$文件名= __DIR__。 '/'。 $基名; //不接受其他目录
$哑剧=($哑剧=和getimagesize($文件名))? $默['默']:$哑剧;
$大小=档案大小($文件名);
$计划生育=的fopen($文件名,RB);
如果(($哑剧和放大器;!&安培; $大小和放大器;&安培; $ FP)){
// 错误。
返回;
}
标题(内容类型:$哑剧。);
标题(内容长度:$大小);
//注:可能头注入通过$基本名
标题(内容处置:附件;文件名=$基名);
标题(内容传输编码:二进制');
标题(缓存控制:必重新验证,后检查= 0,pre-检查= 0');
fpassthru($ FP);
然后设置图片链接指向该文件是这样的:
&LT; IMG SRC =?/图片/ IMG的download.php = imagename.jpgALT =测试&GT;
I want to force user to download images. Not open in browser.
It is possible to use HTML5 this attribute download
but currently only Chrome supports it.
I tried .htaccess
solution but it doesn't work.
<Files *.jpg>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
How can I force download all my images if user click on the link ?
<a href="http://blablabla.com/azerty/abc.jpg" target="_blank" />Download</a>
There's two ways to do this - one with JS, one with PHP.
In JS from this site:
<a href="javascript:void(0);"
onclick="document.execCommand('SaveAs',true,'file.html');"
>Save this page</a>
In PHP create a script named download.php
that is similar to the following code:
<?php
// Force download of image file specified in URL query string and which
// is in the same directory as the download.php script.
if(empty($_GET['img'])) {
header("HTTP/1.0 404 Not Found");
return;
}
$basename = basename($_GET['img']);
$filename = __DIR__ . '/' . $basename; // don't accept other directories
$mime = ($mime = getimagesize($filename)) ? $mime['mime'] : $mime;
$size = filesize($filename);
$fp = fopen($filename, "rb");
if (!($mime && $size && $fp)) {
// Error.
return;
}
header("Content-type: " . $mime);
header("Content-Length: " . $size);
// NOTE: Possible header injection via $basename
header("Content-Disposition: attachment; filename=" . $basename);
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
fpassthru($fp);
Then set the image link to point to this file like this:
<img src="/images/download.php?img=imagename.jpg" alt="test">
这篇关于如何可以强制在浏览器中的图像下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!