【问题标题】:How can I force an Image download in the browser?如何在浏览器中强制下载图像?
【发布时间】:2012-06-18 19:54:48
【问题描述】:

我想强制用户下载图片。没有在浏览器中打开。

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

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

<Files *.jpg>
   ForceType application/octet-stream
   Header set Content-Disposition attachment
</Files>

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

<a href="http://blablabla.com/azerty/abc.jpg" target="_blank" />Download</a>

【问题讨论】:

  • 双引号"attachment"怎么样
  • @AdnanShammout:这真的不会改变任何事情。
  • 那么我认为您应该确保 mod_headers 在您的 php.ini 中未注释
  • 我只知道它有效。仔细检查您的网络服务器配置,如果您觉得不能,请联系通常负责该问题的技术人员(您的系统管理员),另请参阅 ForceType DirectiveHeader Directive

标签: php image .htaccess


【解决方案1】:

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

来自this site的JS:

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

在 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);

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

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

【讨论】:

  • JS 方法在 FF 和 Chrome 中不起作用,需要修改 .htaccess:stackoverflow.com/questions/833015/…
  • 既然这在几个月前就被标记为正确,那你现在为什么会来这里说它是错误的?您链接到的问题的 JS 语法不正确 - 第二个参数必须是布尔值 true,而不是字符串“true”。
  • execCommand 针对这种情况是 IE 特定且非标准的 - msdn.microsoft.com/en-us/library/ms536419(v=vs.85).aspx - 从问题来看,很明显 OP 要求提供跨浏览器兼容规范。 - 然后你不解释为什么(或为什么不)问题中概述的 .htaccess 没有成功。相反,它只是做某事的另一种方式,我敢打赌,早先已经得到了更好的回答,但您甚至没有提供参考。并不是说代码的可读性也可以大大提高。
  • 所以,尽管我在几个月前为 OP 编写的内容有效,但您几乎完全重写了 php,并删除了对我从何处获取它的引用。最重要的是,您重写了 OP 的问题。然后你做出假设(“我敢打赌这已经得到了更好的回答......”),而不用费心去看看你自己是否真的是对的。哇。
【解决方案2】:

改为在您的 .htaccess 中尝试:

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

【讨论】:

    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2011-06-03
    • 2011-09-25
    • 1970-01-01
    • 2012-05-15
    • 2012-07-24
    相关资源
    最近更新 更多