Download images

1

Problem

How do I download multiple images with javascript?

For example, how do I do when I click a button in javascript it automatically accesses the url: link and download the image?

HTML

<button onclick="salvar_imagem()">Salvar Imagem</button>

JAVASCRIPT

<script>
function salvar_imagem(){
     // ir em http://www.bing.com/az/hprichbg/rb/FrenchSunset_PT-BR10590691175_1366x768.jpg e baixar a imagem
}
</script>

I have no idea how this is done.

Note

If this is not possible in JavaScript could someone give me a hint of how to do it in PHP ?

    
asked by anonymous 06.03.2014 / 13:18

3 answers

2

You can load the image onto a canvas and grab the canvas url to save. Here is an example taken from from :

// Pegue uma referencia para o elemento da imagem
var elephant = document.getElementById("elephant");

// Haja quando ela carregar
elephant.addEventListener("load", function () {
var imgCanvas = document.createElement("canvas"),
imgContext = imgCanvas.getContext("2d");

// Tenha certeza que o canvas tem o mesmo tamanho que a imagem
imgCanvas.width = elephant.width;
imgCanvas.height = elephant.height;

// Desenhe a imagem no canvas
imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

// Transforme o canvas em URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");

// Salve
try {
localStorage.setItem("elephant", imgAsDataURL);
}
catch (e) {
console.log("Storage failed: " + e);
}
}, false); 

Good Luck.

    
06.03.2014 / 13:27
4

For security purposes, the browser does not allow you to save images / files directly to the user's machine, what you can do is load the image on the page and ask the user to save the image manually.

    
06.03.2014 / 14:16
2

In fact there is no way to do this via javascript, browsers have a security restriction that does not allow a request to be made to a different server. So who should do this is your backend and not the front end.

    
06.03.2014 / 13:19