React-native-android - How to save an image to the Android file system and view in the phone's 'Gallery'

Larney picture Larney · Jul 22, 2016 · Viewed 16k times · Source

Is it possible to save an image to the android's local file system so it can be viewed from the phone's 'Gallery' and in a folder??

I found this react-native-fs library but after studying the documentation and working through an example I am still unsure if it is possible.

Thanks

Answer

Larney picture Larney · Aug 9, 2016

For anyone having the same problem, here is the solution.

Solution

I am using the File System API from the react-native-fetch-blob library. This is because I tought it was way better documented and easier to understand than the 'react-native-fs' library.

I request an image from the server, receive a base64 and I then save it to the Pictures directory in the android fs.

I save the image like this:

var RNFetchBlob = require('react-native-fetch-blob').default;

const PictureDir = RNFetchBlob.fs.dirs.PictureDir;

getImageAttachment: function(uri_attachment, filename_attachment, mimetype_attachment) {

   return new Promise((RESOLVE, REJECT) => {

   // Fetch attachment
   RNFetchBlob.fetch('GET', config.apiRoot+'/app/'+uri_attachment)
   .then((response) => {

     let base64Str = response.data;

     let imageLocation = PictureDir+'/'+filename_attachment;

     //Save image
     fs.writeFile(imageLocation, base64Str, 'base64');
     console.log("FILE CREATED!!")

     RNFetchBlob.fs.scanFile([ { path : imageLocation, mime : mimetype_attachment } ])
     .then(() => {
       console.log("scan file success")
     })
     .catch((err) => {
       console.log("scan file error")
     })

    }).catch((error) => {
    // error handling
    console.log("Error:", error)
  });
},

The following code that is in the above method refreshes the Gallery otherwise the images would not display untill the phone is turned off and back on again.

RNFetchBlob.fs.scanFile([ { path : imageLocation, mime : mimetype_attachment } ])
.then(() => {
  console.log("scan file success")
})
.catch((err) => {
  console.log("scan file error")
})

Enjoy!