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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.