Download images

Asked

Viewed 5,697 times

1

Problem


How do I download several images with javascript?

For example, how do I when I click on a javascript button it automatically accesses url: http://www.bing.com/az/hprichbg/rb/FrenchSunset_PT-BR10590691175_1366x768.jpg 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 to do that.

Observing

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

  • 1

    You want to save this where? On client or server?

  • On the same customer :)

  • I won’t answer for lack of experience, but I know you can’t save directly on the customer, but there are workarounds. It has the Html5 File System API, or if you want to go further, you can make a client desktop application that obeys a protocol to download it.

3 answers

4

For security reasons, the browser does not allow to save images/files directly to the user’s machine, what can be done is to load the image on the page and request the user to save the image manually.

2

Actually 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 back-end and not the front-end.

2


You can upload the image to a canvas and take the canvas URL to save. Here’s an example from from here:

// 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.

  • Note that this persists the image in the browser’s Storage location, not in user folders. In addition to making subsequent access to the image inconvenient, you may still lose all the images you saved that you saved when cleaning the browsing data.

  • 1

    "Good Luck" was very suggestive... =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.