如何在浏览器中强制下载图像?

时间:2012-06-18 19:54:48

标签: php image .htaccess

我想强制用户下载图片。未在浏览器中打开。

可以使用HTML5此属性download,但目前只有Chrome支持它。

我尝试了.htaccess解决方案,但它不起作用。

<Files *.jpg>
   ForceType application/octet-stream
   Header set Content-Disposition attachment
</Files>

如果用户点击链接,我如何强行下载所有图片?

<a href="http://blablabla.com/azerty/abc.jpg" target="_blank" />Download</a>

2 个答案:

答案 0 :(得分:13)

有两种方法可以做到这一点 - 一个用JS,一个用PHP。

来自this site的JS:

<a href="javascript:void(0);"
 onclick="document.execCommand('SaveAs',true,'file.html');"
 >Save this page</a>

在PHP中,创建一个名为download.php的脚本,类似于以下代码:

<?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);

然后将图像链接设置为指向此文件,如下所示:

<img src="/images/download.php?img=imagename.jpg" alt="test">

答案 1 :(得分:-2)

请在.htaccess中尝试此操作:

<FilesMatch "\.(?i:jpg|gif|png)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>