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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11090272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:44:42  来源:igfitidea点击:

How can I force an Image download in the browser?

phpimage.htaccess

提问by Steffi

I want to force user to download images. Not open in browser.

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

It is possible to use HTML5 this attribute downloadbut currently only Chrome supports it.

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

I tried .htaccesssolution 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>

回答by SickHippie

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

回答by Sebastian Piskorski

Try this in your .htaccess instead:

在你的 .htaccess 中试试这个:

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