如何分享檔案

寮國
Paances Liao

新穎時尚

使用 Web Share API 的 share() 方法

如要分享檔案,請呼叫 navigator.share()。請注意,請務必一律檢查檔案是否可與 navigator.canShare() 共用,並在呼叫 share() 方法之前,確認網站使用的是 HTTPS。

// Assume `blob` is a PNG image file.
const data = {
  files: [
    new File([blob], 'image.png', {
      type: blob.type,
    }),
  ],
  title: 'My title',
  text: 'My text',
};
if (navigator.canShare(data)) {
  await navigator.share(data);
}

瀏覽器支援

  • 89
  • 93
  • 12.1

資料來源

經典風格

如果系統不支援 Web Share API,則最好先提供使用者另一個檔案,讓使用者自行下載檔案,以便手動透過電子郵件、訊息傳遞工具/線上社群網路應用程式等方式手動分享。

瀏覽器支援

  • 15
  • 13
  • 20
  • 10.1

資料來源

漸進增強

當瀏覽器支援 Web Share API,且使用者可以根據支援的檔案類型分享資料時,下列方式就會使用 Web Share API。 如果沒有,系統會改為下載檔案。

const button = document.querySelector('button');
const img =  document.querySelector('img');

// Feature detection
const webShareSupported = 'canShare' in navigator;
// Update the button action text.
button.textContent = webShareSupported ? 'Share' : 'Download';

const shareOrDownload = async (blob, fileName, title, text) => {
  // Using the Web Share API.
  if (webShareSupported) {
    const data = {
      files: [
        new File([blob], fileName, {
          type: blob.type,
        }),
      ],
      title,
      text,
    };
    if (navigator.canShare(data)) {
      try {
        await navigator.share(data);
      } catch (err) {
        if (err.name !== 'AbortError') {
          console.error(err.name, err.message);
        }
      } finally {
        return;
      }
    }
  }
  // Fallback implementation.
  const a = document.createElement('a');
  a.download = fileName;
  a.style.display = 'none';
  a.href = URL.createObjectURL(blob);
  a.addEventListener('click', () => {
    setTimeout(() => {
      URL.revokeObjectURL(a.href);
      a.remove();
    }, 1000)
  });
  document.body.append(a);
  a.click();
};

button.addEventListener('click', async () => {
  const blob = await fetch(img.src).then(res => res.blob());
  await shareOrDownload(blob, 'cat.png', 'Cat in the snow', 'Getting cold feet…');
});

其他資訊

示範

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      rel="icon"
      href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
    />
    <title></title>
    <link rel="stylesheet" href="style.css" />
    <!-- TODO: Devsite - Removed inline handlers -->
    <!-- <script src="script.js" type="module"></script> -->
  </head>
  <body>
    <h1>Share a file</h1>
    <img
      width="200"
      height="200"
      alt="A cat walking in the snow."
      src="cat.png"
    />
    <button type=button></button>
  </body>
</html>

CSS


        :root {
  color-scheme: dark light;
}

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 1rem;
  font-family: system-ui, sans-serif;
}

img,
video {
  height: auto;
  max-width: 100%;
  display: block;
}

button {
  margin: 1rem;
}
        

JS


        const button = document.querySelector('button');
const img =  document.querySelector('img');

const webShareSupported = 'canShare' in navigator;
button.textContent = webShareSupported ? 'Share' : 'Download';

const shareOrDownload = async (blob, fileName, title, text) => {
  if (webShareSupported) {
    const data = {
      files: [
        new File([blob], fileName, {
          type: blob.type,
        }),
      ],
      title,
      text,
    };
    if (navigator.canShare(data)) {
      try {
        await navigator.share(data);
      } catch (err) {
        if (err.name !== 'AbortError') {
          console.error(err.name, err.message);
        }
      } finally {
        return;
      }
    }
  }
  // Fallback
  const a = document.createElement('a');
  a.download = fileName;
  a.style.display = 'none';
  a.href = URL.createObjectURL(blob);
  a.addEventListener('click', () => {
    setTimeout(() => {
      URL.revokeObjectURL(a.href);
      a.remove();
    }, 1000)
  });
  document.body.append(a);
  a.click();
};

button.addEventListener('click', async () => {
  const blob = await fetch(img.src).then(res => res.blob());
  await shareOrDownload(blob, 'cat.png', 'Cat in the snow', 'Getting cold feet…');
});