How to share a file using Web Share Target API?

753 views Asked by At

How can I share a file using Web Share Target API?

I managed to make my Progressive Web App appear when I try to share a file from the gallery app on my phone. My question is how can I take the file and send it to the server or fill a HTML input with type="file" with the shared file?

This is what I have right now

In manifest.json

    "share_target": {
    "action": "/qtransfer-p/send.php",
    "method": "POST",
    "enctype": "multipart/form-data",
    "params": {
      "title": "name",
      "text": "description",
      "url": "link",
      "files": [
        {
          "name": "fileToUpload",
          "accept": [".pdf", ".png", ".jpeg", ".doc", ".docx", ".pdf", ".xls", ".xlsx", ".txt", ".mp4", ".mp3", ".wav", ".rar", ".zip"]
        }
      ]
    }
}

In sw.js (service worker)

self.addEventListener('fetch', event => {
  const url = new URL(event.request.clone().url);
  // If this is an incoming POST request for the
  // registered "action" URL, respond to it.
  if (event.request.method === 'POST' &&
      url.pathname === '/qtransfer-p/send.php') {
      event.respondWith(Response.redirect('/qtransfer-p/send.php'));
      event.waitUntil((async () => {
        console.log("1");
        const data = await event.request.clone().formData();
        console.log("2");
        console.log(data);
        const client = await self.clients.get(event.resultingClientId || event.clientId);
        console.log("3");
        const file = data.get("fileToUpload");
        console.log("file", file);
        client.postMessage({ file, action: 'load-file' });
      })());
      console.log("ok");
      return 0;
  }
});

Right now, when I share a photo, I get in console:

1

ok

Uncaught (in promise) TypeError: Failed to fetch

So I think the problem is on the "const data = await event.request.clone().formData();".

Someone please help! I am trying to solve this for 2 weeks!

1

There are 1 answers

4
Jeff Posnick On

If you'd like to send a file directly to your web server, you can skip the service worker involvement.

Your current manifest.json setup will result in a POST request being sent to the /qtransfer-p/send.php at your origin, encoded as multipart/form-data, whenever someone shares a supported file to your installed PWA.

As long as you don't intercept that request in a service worker, I believe it will just be sent directly like any other HTTP POST, and could be processed server-side.