9

ユーザーに画像のダウンロードを強制したい。ブラウザで開かない。

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

2 に答える 2

14

これには 2 つの方法があります。1 つは JS を使用する方法、もう 1 つは PHP を使用する方法です。

このサイトのJSで:

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

PHPdownload.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">
于 2012-06-18T20:13:12.653 に答える
-2

代わりに .htaccess でこれを試してください:

<FilesMatch "\.(?i:jpg|gif|png)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>
于 2014-11-13T20:03:24.010 に答える