نحوه اشتراک گذاری فایل ها

کاخ لیائو
Palances Liao

روش مدرن

استفاده از متد share() در Web Share API

برای اشتراک‌گذاری فایل‌ها، تابع 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);
}

Browser Support

  • کروم: ۱۲۸.
  • لبه: ۹۳.
  • فایرفاکس: پشت یک پرچم.
  • سافاری: ۱۲.۱.

Source

روش کلاسیک

اگر از Web Share API پشتیبانی نمی‌شود، بهترین گزینه بعدی که می‌توان به کاربر ارائه داد، این است که به کاربر اجازه دهید فایل را دانلود کند تا بتواند آن را به صورت دستی، مثلاً از طریق ایمیل یا از طریق یک پیام‌رسان یا برنامه شبکه اجتماعی آنلاین، به اشتراک بگذارد.

Browser Support

  • کروم: ۱۵.
  • لبه: ۱۳.
  • فایرفاکس: 20.
  • سافاری: ۱۰.۱.

Source

بهبود تدریجی

روش زیر از 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…');
});

مطالعه بیشتر

نسخه آزمایشی

اچ‌تی‌ام‌ال

<!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>

سی اس اس


        :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;
}
        

جی‌اس


        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…');
});