Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 799
Steffi Avatar asked Jun 18 '12 19:06

Steffi


People also ask

How do I force a download on browser?

In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead. The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.

How do I download an image from my browser?

To save an image from a website in Chrome, users can usually just right-click on it and select “Save image” from the menu.

How do I download an image URL?

Click on the Download Image from URL button, the field will appear on the right. Enter the full web address of the image. Click on the arrow to the right of the field and select the Force Check checkbox. Then click the Save button.

How do I download something as an image?

Or, right-click on the file and choose Save as. Images: Right-click on the image and choose Save Image As. Videos: Point to the video. Click Download.


1 Answers

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">
like image 87
SickHippie Avatar answered Nov 01 '22 15:11

SickHippie