Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share files with capacitor share plugin

I need to share a PDF file. I am using CapacitorJS for native functionality.

let shareRet = await Share.share({
  title: 'See cool stuff',
  text: 'Really awesome thing you need to see right meow',
  url: 'http://ionicframework.com/',
  dialogTitle: 'Share with buddies'
});

This is from the example. But I have my data as a base64 string. Is there a way to share this as an attachment?

like image 509
johnbraum Avatar asked Jun 21 '26 18:06

johnbraum


2 Answers

This code works for me on iOS and Android:

import { Directory, Filesystem } from '@capacitor/filesystem';
import { Share } from '@capacitor/share';

function share(fileName: string, base64Data: string) {
  return Filesystem.writeFile({
    path: fileName,
    data: base64Data,
    directory: Directory.Cache
  })
    .then(() => {
      return Filesystem.getUri({
        directory: Directory.Cache,
        path: fileName
      });
    })
    .then((uriResult) => {
      return Share.share({
        title: fileName,
        text: fileName,
        url: uriResult.uri,
      });
    });
}
like image 154
kazinov Avatar answered Jun 23 '26 06:06

kazinov


Try using files: [] property, this code might help if you wanna send a binary file like image via email or instagram or whatsapp my capacitor version 4.x

import { Share } from '@capacitor/share';


shareImage() {
try {
//1. get image as base64
// this function just downloads the file from link and converts to base64

      const b64image = await this._mediaUploadService.downloadImage(this.selectedImages[0]) as string;
      


//2.  save file in cache
      await Filesystem.writeFile({
        path: this.selectedImages[0],
        data: b64image,
        directory: Directory.Cache
      });



//3. get full uri of the saved image
      let imgData = await Filesystem.getUri({
        path: this.selectedImages[0],
        directory: Directory.Cache
      });

// share using @capacitor/share plugin
      Share.share({
        text: "hello",
        dialogTitle: "Share via",
        files: [imgData.uri],
      });
    } catch (e) {
         console.error(e);
    }
}
like image 23
Pratik Agarwal Avatar answered Jun 23 '26 08:06

Pratik Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!