Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

php - How can I force an Image download in the browser?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...