0

How can i download an image when the user presses a button on the web page. I don't want to use <a href download="file"> as it doesn't work on some devices. How can i do this using JavaScript

Sukrit Kumar
  • 375
  • 4
  • 20
  • 1
    Possible duplicate of [Force Download an Image Using Javascript](http://stackoverflow.com/questions/6796974/force-download-an-image-using-javascript) – Mike Cluck May 10 '16 at 17:35

1 Answers1

2

You need to add download attr to <a></a> link, or by event of other element:

$('button.download', modal).on('click', function (e) {
  e.preventDefault();

  var url = ""; // Some URL.
  var fileName = "image.jpeg"; // Some File name

  var a = $('<a href="' + url + '"></a>')
    .attr('download', fileName)
    .appendTo('body');

  a.click(function () {
    a[0].click();
    $(this).remove();
  });

  a.trigger('click');
});

[EDIT] In case of you don't want to use it, you <a></a> link need to have these headers in the server response of the file to download:

Content-Type: application/force-download

Content-Disposition: attachment; filename="image.jpeg"

Content-Transfer-Encoding: binary

jgdev
  • 509
  • 3
  • 7