LoginSignup
4
2

More than 3 years have passed since last update.

JavaScript でサーバ上にある画像を zip でまとめてダウンロードする

Last updated at Posted at 2020-07-02

何をしたいの

既存のサイトやウェブアプリ上にある画像を取得してきて zip したい。

サーバ上にある画像をダウンロードするコード

ここは素直に XMLHttpRequestで取得する。

const getImage = (imageUrl) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', imageUrl, true);
    xhr.responseType = "blob";
    xhr.onload = (e) => {
      // 取得した画像データが e.currentTarget.response にある
      resolve(e.currentTarget.response);
    };
    xhr.send();
  });
};

ダウンロードしたものを zip にまとめる

JSZip というライブラリを使うと簡単。

const generateZip = (images) => {
  return new Promise((resolve, reject) => {
    const zip = new JSZip();
    images.forEach((imageData, i) => {
      zip.file(`image${String(i).padStart(3, '0')}`, imageData);
    });
    zip.generateAsync({ type: "blob" }).then(resolve);
  });
};

画像だけまとめているけど、 zip.file(ファイル名, ファイルの内容) を使ってテキストファイル等別のファイルも纏められる。

組み合わせるとこうなる

const imageUrls = [
  'https://chrysanthemum94.example.com/imageA.png',
  'https://chrysanthemum94.example.com/imageB.png',
  'https://chrysanthemum94.example.com/imageC.png',
];
Promise.all(
  imageUrls.map((url) => {return getImage(url);})
).then((blobs) => {
  generateZip(blobs).then((zip) => {
    console.log(URL.createObjectURL(zip))
  });
});

まぁ、でも

一般にこういうのってサーバサイドで生成させる方が簡単な気はする。
静的なサイトなら最初からそういう zip ファイルを提供する方がいいだろうし。
サーバサイドをうんぬんするのが難しい事由がある場合に。

4
2
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
4
2