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

کاخ لیائو
Palances Liao

روش مدرن

استفاده از API هدف اشتراک‌گذاری وب

ابتدا، یک تابع share_target در مانیفست برنامه وب خود تعریف کنید که شامل یک action (URL شما که فایل‌های اشتراکی را مدیریت می‌کند)، یک method ( "POST" برای فایل‌ها) و یک enctype ( "multipart/form-data" برای فایل‌ها) و یک شیء params باشد که شامل یک ویژگی files با آرایه‌ای از اشیاء با یک name و یک ویژگی accept است که انواع فایل‌های قابل اشتراک و نام مورد نیاز برای دریافت آنها را فهرست می‌کند.

{
  "share_target": {
    "action": "/receive-files/",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "files": [
        {
          "name": "image",
          "accept": ["image/jpeg", "image/png", "image/webp", "image/gif"]
        }
      ]
    }
  }
}

سپس باید درخواست‌های POST ورودی را در سرویس ورکر مدیریت کنید. این فایل به طور موقت در حافظه پنهان رسانه ذخیره می‌شود، بنابراین می‌تواند در کلاینت مورد استفاده قرار گیرد. این کار را می‌توان با هدایت برنامه به یک URL با یک پارامتر query نشانگر خاص مانند share-target انجام داد.

self.addEventListener('fetch', (fetchEvent) => {
  if (fetchEvent.request.url.endsWith('/receive-files/') && fetchEvent.request.method === 'POST') {
    return fetchEvent.respondWith(
      (async () => {
        const formData = await fetchEvent.request.formData();
        const image = formData.get('image');
        const keys = await caches.keys();
        const mediaCache = await caches.open(keys.filter((key) => key.startsWith('media'))[0]);
        await mediaCache.put('shared-image', new Response(image));
        return Response.redirect('./?share-target', 303);
      })(),
    );
  }
});

در نهایت، شما باید فایل را در کلاینت استفاده کنید.

window.addEventListener('load', async () => {
  if (location.search.includes('share-target')) {
    const keys = await caches.keys();
    const mediaCache = await caches.open(
      keys.filter((key) => key.startsWith('media'))[0],
    );
    const image = await mediaCache.match('shared-image');
    if (image) {
      const blob = await image.blob();
      await mediaCache.delete('shared-image');
      // Handle the shared file somehow.
    }
  }
});

مطالعه بیشتر

نسخه آزمایشی

اچ‌تی‌ام‌ال

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="manifest" href="manifest.json" />
    <title>How to receive shared files</title>
    <link rel="stylesheet" href="style.css" />
    <!-- TODO: Devsite - Removed inline handlers -->
    <!-- <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', async () => {
          const registration = await navigator.serviceWorker.register(
            'sw.js',
          );
          console.log(
            'Service worker registered for scope',
            registration.scope,
          );
        });
      }
    </script>
    <script src="script.js" type="module"></script> -->
  </head>
  <body>
    <h1>How to receive shared files</h1>
    <p>Install the app. After the installation, try sharing an image to it from another app.
  </body>
</html>

سی‌اس‌اس


        html {
  box-sizing: border-box;
  font-family: system-ui, sans-serif;
  color-scheme: dark light;
}

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

body {
  margin: 1rem;
}

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

جی‌اس


        window.addEventListener('load', async () => {
  if (location.search.includes('share-target')) {
    const keys = await caches.keys();
    const mediaCache = await caches.open(
      keys.filter((key) => key.startsWith('media'))[0],
    );
    const image = await mediaCache.match('shared-image');
    if (image) {
      const blob = await image.blob();
      await mediaCache.delete('shared-image');
      // Handle the shared file somehow.
    }
  }
});