Search code examples
androidreact-nativeandroid-storagenode.js-fsreact-native-fs

Unable to overwrite image in file path on android (React Native)


I am unable to overwrite files when storing them on android's external storage.

I have tried both react-native-fs and rn-fetch-blob but they both have the same result.

I've tried looking for more permissions to add, but I have them all (Allow read and write). I have also tried to delete the file prior to writing the file, but I am unable to do this as well, it seems like nothing works how it should.

Here is my code where I attempt to writeFile, I wonder what could be wrong?

const takeSnapshot = () => {
  if (canvas.current) {
    const snapshot = canvas.current.makeImageSnapshot();
    const data = snapshot?.encodeToBase64(ImageFormat.JPEG, 100);
    if (data) {
      const fileName = 'skiaImgRef.jpg';
      var skiaPath = `file://${RNFS.DocumentDirectoryPath}/${fileName}`;

      // write the file
      RNFS.writeFile(skiaPath, data, 'base64')
        .then(success => {
          getMediaThumb(
            `file://${RNFS.DocumentDirectoryPath}/${fileName}`,
            0,
          );
          passOnImageSkia(
            `file://${RNFS.DocumentDirectoryPath}/${fileName}`,
          );
        })
        .catch(err => {
          console.log(err.message);
        });
    }
  }
};

Solution

  • The problem is Android is cashing them so if you add Date.now() to the file name "skiaImgRef${Date.now()}.jpg", and then when you want to update it, just delete the old one and replace it with the updated one.