如何可以强制在浏览器中的图像下载?器中、图像

2023-09-02 00:21:40 作者:其实ァ思念、依旧

我想强迫用户下载图像。在不打开浏览器。

可以使用HTML5这个属性下载不过目前只有Chrome支持它。

我试过的.htaccess 解决方案,但它不能正常工作。

 <文件* .JPG>
   ForceType指令的应用程序/八位字节流
   头中设置内容处置附件
< /文件>
 

我如何可以强制下载所有我的图片,如果链接的用户点击?

 < A HREF =htt​​p://blablabla.com/azerty/abc.jpg目标=_空白/>下载< / A>
 

解决方案

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

浏览器中如何快速下载SVG图片

在JS从本网站:

 < A HREF =JavaScript的:无效(0);
 的onclick =document.execCommand('另存为',真正的'file.html');
 >保存该页面< / A>
 

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

 < PHP
//图像文件的强制下载指定的URL查询字符串并
//是在同一目录下的download.php脚本。

如果(空($ _ GET ['IMG'])){
   标题(HTTP / 1.0 404未找​​到);
   返回;
}

$基本名=基名($ _ GET ['IMG']);
$文件名= __DIR__。 '/'。 $基名; //不接受其他目录

$哑剧=($哑剧=和getimagesize($文件名))? $默['默']:$哑剧;
$大小=档案大小($文件名);
$计划生育=的fopen($文件名,RB);
如果(($哑剧和放大器;!&安培; $大小和放大器;&安培; $ FP)){
  // 错误。
  返回;
}

标题(内容类型:$哑剧。);
标题(内容长度:$大小);
//注:可能头注入通过$基本名
标题(内容处置:附件;文件名=$基名);
标题(内容传输编码:二进制');
标题(缓存控制:必重新验证,后检查= 0,pre-检查= 0');
fpassthru($ FP);
 

然后设置图片链接指向该文件是这样的:

 < IMG SRC =?/图片/ IMG的download.php = imagename.jpgALT =测试>
 

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">