0
0

More than 3 years have passed since last update.

JavaScriptで外部画像ファイルを一括ダウンロード

Last updated at Posted at 2021-09-19

chromeのみで確認
外部ファイルを表示させているサイトから画像をダウンロードしたい時、download属性だけでは機能しないので
クロスドメイン制限回避の為にこれを使うといいかも

sample.js
function geturl(index) {
  const gallery = document.getElementsByClassName("classname");
  let url = gallery[index].getAttribute("href");
  return url;
}

function galleryDownload(i) {
  return new Promise((resolve) => {
    setTimeout(() => {
      let url = geturl(i);
      console.log(url);
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = function () {
        const dataurl = (window.URL || window.webkitURL).createObjectURL(
          this.response
        );
        let a = document.createElement("a");
        a.href = dataurl;
        a.setAttribute("download", url);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(dataurl);
        resolve("wait");
      };
      xhr.send();
    }, 1000);
  });
}

const gallery = document.getElementsByClassName("classname");
let length = gallery.length;
console.log(length);

async function Download() {
  for (let i = 0; i <= length; i++) {
    await galleryDownload(i);
  }
}

Download();

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0