如何在浏览器中强制下载图像? [英] How can I force an Image download in the browser?

查看:40
本文介绍了如何在浏览器中强制下载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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>

推荐答案

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

There's two ways to do this - one with JS, one with PHP.

来自本网站的JS:

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

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

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

这篇关于如何在浏览器中强制下载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆