Reputation: 10412
I want to download a image file (jpeg image) to the user files system when user selects a photo and clicks a button. So far I searched and found this link and also this
I saw in one blog that downloadify when used with jszip can enable this feature but it didn't specify any farther on this. Does any one know how to download the images. I have the links to the images and i just want the user to download it on his system rather than again query the server.
Can anyone provide me with an example please.
Upvotes: 6
Views: 56937
Reputation: 123
Needed for a project to make a custom context(right-click) menu with a custom download image button.
Here is an answer using pure javascript:
const imageElement = document.getElementById("YourImage").getAttribute("src");
const saveImage = (downloadUrl: string) => {
const downloadImage = document.createElement("a");
document.body.appendChild(downloadImage);
downloadImage.setAttribute("download", "image");
downloadImage.href = downloadUrl;
downloadImage.click();
downloadImage.remove();
};
saveImage(imageElement)
Upvotes: 2
Reputation: 7631
Use the HTML5 download
attribute.
As a choice you can set filename as an attribute value.
<a href="/images/image-name.jpg" download="new-image-name.jpg">
Upvotes: 7
Reputation: 10412
Finally I did it. For anyone who may need this in the future here is how I did it using jquery
jQuery.ajax({
url: 'http://localhost:8080/yourwebsite/servlet?img=' + document.getElementById(id).alt,
//data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
// success: function() { alert("Success"); },
// error: function() { alert('Failed!'); },
// beforeSend: setHeader
});
this I had to do come across the problem of cross domain http requests which are usually blocked by most websites unless you follow some lengthy process. So, I made it simpler and called a get method in my servlet and passed it the url of the image from which it downloaded the image.This is much easier to do and even easier then this if you are on the same domain but that didn't meet my requirements and this code worked for me :)
Upvotes: 1
Reputation: 110892
You can load the image in an canvas element get the data url of the canvas and open a new window with the data url as source. Take a look at this example: https://gist.github.com/1875132
Upvotes: 5