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

Ste*_*ffi 9 php .htaccess image

我想强迫用户下载图像.未在浏览器中打开.

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

我试过.htaccess解决方案,但它不起作用.

<Files *.jpg>
   ForceType application/octet-stream
   Header set Content-Disposition attachment
</Files>
Run Code Online (Sandbox Code Playgroud)

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

<a href="http://blablabla.com/azerty/abc.jpg" target="_blank" />Download</a>
Run Code Online (Sandbox Code Playgroud)

Sic*_*pie 13

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

这个站点的 JS中:

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

在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);
Run Code Online (Sandbox Code Playgroud)

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

<img src="/images/download.php?img=imagename.jpg" alt="test">
Run Code Online (Sandbox Code Playgroud)

  • JS方法不适用于FF和Chrome,你需要修改.htaccess:http://stackoverflow.com/questions/833015/does-execcommand-saveas-work-in-firefox (2认同)