How to share a local file using SocialShare Plugin in Ionic5 project?

1.5k Views Asked by At

I am pretty new to Javascript and Ionic framework . I want to share a local file which has the path "/assets/input.json" using SocialShare Plugin and I want to share this local file which is of .json extension into a .txt file through the app.

Can anyone please help with how should I use this plugin to access my local file and how can I convert it into a text file for sharing it.

2

There are 2 best solutions below

0
On BEST ANSWER

Try this Reference : https://www.npmjs.com/package/cordova-plugin-x-socialsharing

var options = {
  message: 'share this', // not supported on some apps (Facebook, Instagram)
  subject: 'the subject', // fi. for email
  files: ['', ''], // an array of filenames either locally or remotely
  url: 'https://www.website.com/foo/#bar?a=b',
  chooserTitle: 'Pick an app', // Android only, you can override the default share sheet title
  appPackageName: 'com.apple.social.facebook', // Android only, you can provide id of the App you want to share with
  iPadCoordinates: '0,0,0,0' //IOS only iPadCoordinates for where the popover should be point.  Format with x,y,width,height
};

For file conversion from .json to .txt you can read & write file using js (https://www.websparrow.org/web/how-to-create-and-save-text-file-in-javascript) and ionic libraries https://ionicframework.com/docs/native/file

0
On

Rather than Social Sharing , I would suggest to use Filesharer , In social sharing I really doubt that you can share a local file from one of your folder. I also have the similar requirement and Filesharer is a perfect plugin for that, below is the code you can try.

async shareLocalFile() {
   console.log('Sharing files...')
   this.http.get('/assets/input.json', { responseType: 'blob'})
   .subscribe( res => {
     const reader = new FileReader();
     reader.onloadend = () => {
       const result = reader.result as string;
       const base64Data = result.split(',')[1]
       FileSharer.share({
         filename:  'input.txt',
         base64Data,
         contentType:'application/txt'
       });
     }reader.readAsDataURL(res);
  })
}