Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a single Base64 URL Image via the Web share API?

So, I need to share a base64 Image string using the Web Share API on TypeScript.

Would it be ok if I passed the base64 string as the url parameter like this:

  var base64url = "data:image/octet-stream;base64,/9j/4AAQSkZ...."
  navigator.share({
    title: 'Hello',
    text: 'Check out this image!',
    url: base64url ,
  })

Or do I need to have a Files Array and use Web Share API v2 ? If so, how do I implement it, all I have is a base64 string and the examples I could found were too confusing.

I am a noob in this matter so some help would be greatly appreciated!

like image 504
Ben Avatar asked Apr 16 '20 12:04

Ben


1 Answers

As mentioned in the comments, sharing the url in the url field won't end up in a nice result for your users.

You can use Web Share API v2 with the following code:

const base64url = "data:image/octet-stream;base64,/9j/4AAQSkZ...."
const blob = await (await fetch(base64url)).blob();
const file = new File([blob], 'fileName.png', { type: blob.type });
navigator.share({
  title: 'Hello',
  text: 'Check out this image!',
  files: [file],
})

You might have to tweak the extension and mime type depending on your actual image urls.

Be aware though that v2 is currently only available on Android Chrome (I can't find a good source for that but I just did this on a project). You can check for availability at run time by using navigator.canShare().

like image 185
Alex de Boutray Avatar answered Nov 09 '22 19:11

Alex de Boutray