Search code examples
imageandroid-galleryreact-nativereact-native-fs

Saved images to Gallery only display when phone is restarted - React-Native Android


I am using the File System API from the react-native-fetch-blob library.

I request an image from the server, receive a base64 and I then save it to 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!!")

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

Problem
The image saves successfully but when I open the android's Gallery it is not visible. But when I turn off and on the Android emulator it is then visible in the Gallery.

Question
How can I view the image in the Android's Gallery without having to restart the emulator?


Solution


I added this to the above method after the file is created:

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

Thanks you @Xeijp.


Solution

  • In Android, to make an image visible in gallery you need to use 'media scanner' on that file. react-native-fetch-blob does provides an API for this

    fs.scanFile(path_of_the_file)
    

    document