Will
Will

Reputation:

Download a picture OnClick

How do you actually download a picture when you click on it? Is there some kind of a javascript code to do just that? Here is how i show the image with pure HTML.

<a href="#"><img src="myPic.png" border="0"></a>

Upvotes: 3

Views: 21420

Answers (4)

Greg Jones
Greg Jones

Reputation: 11

I trick this out a bit - I zip the picture and put it somewhere. Then, instead of using a fancy script or server-side stuff, I make the picture's link the location of the .zip file. The user get's warned/asked if they want to download this zip and voila...

But this is usually in an area where the user is someone who would want the image...

Upvotes: 1

DisgruntledGoat
DisgruntledGoat

Reputation: 72530

Most people right-click on the image and choose "Save image as..."

The alternate is to link to use a server-side script that sets a "Content-type" and "Content-disposition" header. In PHP, that would be something like this example from the docs:

header('Content-Type: image/png'); // or 'image/jpg' or 'image/gif'
header('Content-Disposition: attachment; filename="filename.png"');
readfile('original.png');

UPDATE: Since you say the image is generated by a PHP script in the first place, there are a few options:

  • Put the URL (sig.php?...) as the parameter to readfile. This will mean double processing for anyone who clicks to download.
  • Cache the output from your image generation script to the filesystem, then pass that file to readfile.
  • Edit the image generation script to accept an extra parameter like mode=download and then where you are about to output the image, if the parameter is present, set those two headers above.

Upvotes: 2

Quentin
Quentin

Reputation: 943571

Assuming by "download" you mean "Cause the user's browser to throw up the 'save or open' dialogue" — you can't.

You could link to another URL offering the same file but with the Content-Disposition header set to attachment. The specifics of how you would provide such a resource at that URL would depend on the server side capabilities on offer to you.

Upvotes: 2

Marius
Marius

Reputation: 58931

Do you want to open the picture in a new window/tab? Or do you want to download it to the users computer? If you want the user to save the image, then you need to set the content-type of the file they receive:

<?php
$file = $_GET['file'];

header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary"); 
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);
?>

Remember to check the input so people can't download source files.

Upvotes: -2

Related Questions