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
-
1Possible duplicate of Force Download an Image Using JavascriptMike Cluck– Mike Cluck2016-05-10 17:35:28 +00:00Commented May 10, 2016 at 17:35
Add a comment
|
1 Answer
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