4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Web Share API を使用して iOS で複数画像をカメラロールに保存する

Posted at

要件

iOSでダウンロードボタンをクリックして ファイル ではなく カメラロール に複数画像を保存させる
下記サンプルでは imageUrls で定義されているものが対象
iOS以外はaタグに画像ファイル配置してダウンロードさせる

js
document.getElementById('js-download').addEventListener('click', async () => {
  const imageUrls = [
    '/150x150.png',
    '/1200x150.png',
  ];

  if (iOS) { // iOSかの判定は別途行う
    Promise.all(imageUrls.map(imageUrl => fetch(imageUrl).then(response => response.blob())))
      .then(blobs => {
        const files = blobs.map((blob, index) => new File([blob], `image${index}.png`, {type: 'image/png'}));
        if (navigator.share) {
          navigator.share({
            files,
            title: 'タイトル',
            text: 'テキスト',
          });
        }
      });
  } else {
    imageUrls.forEach((imageUrl, index) => {
      fetch(imageUrl)
        .then(response => response.blob())
        .then(blob => {
          const file = new File([blob], `image${index}.png`, {type: 'image/png'});
          const a = document.createElement('a');
          a.href = URL.createObjectURL(file);
          a.download = file.name;
          a.click();
        });
    });
  }

});

Web Share API

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?