简体   繁体   English

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

[英]How can I force an Image download in the browser?

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. 可以使用HTML5此属性 download但目前只有Chrome支持它。

I tried .htaccess solution but it doesn't work. 我试过.htaccess解决方案,但它不起作用。

<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. 有两种方法可以做到这一点 - 一个用JS,一个用PHP。

In JS from this site : 这个站点的 JS中:

<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中创建一个名为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);

Then set the image link to point to this file like this: 然后将图像链接设置为指向此文件,如下所示:

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

Try this in your .htaccess instead: 请在.htaccess中尝试此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM