3

I'm using Javascript in the Developer Console/Inspect Element (in Firefox and/or Chrome, either one).

I'm wanting to download multiple image files from a link - let's say for example this: https://i.etsystatic.com/9228829/r/il/d729fb/992816422/il_fullxfull.992816422_35w3.jpg

So in the console I have that link (and others) as a string and for each, I'm trying to download them directly to my computer. I can trigger a download, but it either a) open in a new tab instead of downloading, b) downloads an empty image file.

I've tried probably 5 different functions from StackOverflow now but none appear to work. Thoughts?

Example code (found on internet):

function download(filename, filelink){
  var link = document.createElement('a');
  link.href = filelink;
  link.download=true;
  document.body.appendChild(link);
  //link.target = "self";
  link.click();
  console.log(link);
  document.body.removeChild(link);
}

var imageToDownload = "https://i.etsystatic.com/9228829/r/il/d729fb/992816422/il_fullxfull.992816422_35w3.jpg"

download(("image.jpg"), imageToDownload);

Here's a second download function that DOES download, but the file is empty. yes, I'm aware that it's looking for text etc, but I can't modify it to be for images:

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  //element.setAttribute('href', 'data:jpg/image;base64');
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}
JackNapier
  • 318
  • 4
  • 14

2 Answers2

3
link.href = filelink;
link.download=true;

The above code will not work. The download attribute of the anchor tag should point to the link where the file to be downloaded is hosted. Only then on clicking the anchor tag the download will be triggered automatically.

Code that works:

var url = 'your url goes here';
var elem = document.createElement('a');
elem.href = url;
elem.download = url;
elem.id="downloadAnchor";
document.body.appendChild(elem);
$('#downloadAnchor').click();

You check the detailed answer in this question

Evan MJ
  • 1,967
  • 13
  • 16
0

Just make:

link.download=filelink;

and remove:

document.body.removeChild(link);
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83