0

Possible Duplicate:
Force Download an Image Using Javascript

Basically I want to have the option for a user to just click a download button and download an image (rather having having to right-click or drag and drop). I read another post on here that offered a PHP solution, however if this can be done entirely in javascript I would much prefer that option. So, can it be done?

Community
  • 1
  • 1
Ian
  • 1,850
  • 6
  • 23
  • 38

2 Answers2

1

Force to open it in a new window.

$('img.class').click(function(){
window.open($(this).href,'image');});

The browser will still render it as an image, however. There's no way of forcing the browser to download an image without setting content-disposition to download and/or using .htacess, which will trigger a download link everytime the image is downloaded. I can tell u a server side solution, but I don't think that's what you want

SoWhat
  • 5,564
  • 2
  • 28
  • 59
  • 1
    +1 one, simple and elegant. I'm using this with an anchor element that links directly to the image, then preventing the default. If javascript is not enabled, it opens the normal link, otherwise this is executed : `$('.anchor-class').click( function(e) { e.preventDefault(); window.open($(this).attr('href')); });` – brasofilo Jan 03 '13 at 20:48
  • Please tell, server side solution might help me. – Rahul Bali Jun 05 '16 at 12:12
1

The Browsers always try to interpret the content you give them. If the Browser thinks, it can handle it, they will take the according action. In the case of an image - display it. You can't change that behaviour. You can only trick the browser by telling him, it's not the content he thinks it is by setting the "wrong" content-type, which forces the browser to display the "download" option. Via javascript you can only open the image in a new window and let the user download with rightclick/save as.

Christoph
  • 50,121
  • 21
  • 99
  • 128
  • I'm going to take your word for it since nobody else had an answer and you seem confident. Thank you. – Ian Feb 06 '12 at 21:32