1

I want my users to be able to download images from my website using jQuery. For example, I have an image like this below on my website. When user clicks "Download" button that image must be downloaded to user system. What can I do to achieve this?

<div class="download"><img src="http://m.com/hello.png"><div>

EDIT : PHP code is also welcome, for example download.php?url=http://m.com/hello.png,

PS: http://m.com/hello.png is an external URL.

maksimov
  • 5,792
  • 1
  • 30
  • 38
Vishnu Simbu
  • 175
  • 1
  • 3
  • 13

3 Answers3

3

For server side, you could direct the image click to a PHP page that would force the download.

On your HTML page, you would have:

If PNG file

<a href="download.php?ext=png"><img src="hello.png" /></a>

or if JPG file

<a href="download.php?ext=jpg"><img src="hello.jpg" /></a>

Then a PHP page download.php as shown below

<?php
if($_GET['ext'] == 'png') {
    $ext = 'png';
} elseif($_GET['ext'] == 'jpg') {
    $ext = 'jpg';
}

header('Content-disposition: attachment; filename=Name-of-Image.'.$ext);
header('Content-type: image/'.$ext);
readfile('http://m.com/hello.'.$ext);

?>
adamdehaven
  • 5,890
  • 10
  • 61
  • 84
0

PHP Code:

header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="filename.png"');
readfile('hello.png');
Learner
  • 3,904
  • 6
  • 29
  • 44
0

You will not be able to do it reliably without using PHP. I found a previous question on this website that can assist you with this: Force Download an Image Using Javascript

Actually there is a method that relies on HTML5 in there, but I'm not quite sure you could consider that reliable yet.

Community
  • 1
  • 1
kyle.stearns
  • 2,326
  • 21
  • 30