React Native file handling - delete image

23.5k views Asked by At

I am using react-native-camera for clicking pictures. I get a file path like : "file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg" in the data from the Camera which I am storing in the state. I am able to use this as the source for displaying the Image using the Image component "Image source={{uri: this.props.note.imagePath.path}}" and it is displaying properly.

Now I want to add delete image functionality. Can someone suggest on how to access this image in the phone using the path mentioned above and delete it from the phone.

I checked the react-native-filesystem but when I used the checkIfFileExists function passing in this path I got that the file doesn't exist. Not sure what is going wrong.

async checkIfFileExists(path) {

const fileExists = await FileSystem.fileExists(path);
//const directoryExists = await FileSystem.directoryExists('my-directory/my-file.txt');
console.log(`file exists: ${fileExists}`);
//console.log(`directory exists: ${directoryExists}`);
}


deleteNoteImage (note) {

console.log(note.imagePath.path);

//check if file exists
this.checkIfFileExists(note.imagePath.path);
//console.log();

note.imagePath = null;
this.updateNote(note);
}

remote debugging snapshot

3

There are 3 answers

2
Aman Agarwal On BEST ANSWER

So I was able to do it using react-native-fs

The path needs to be declared as follows:

var RNFS = require('react-native-fs');

const dirPicutures = `${RNFS.ExternalStorageDirectoryPath}/Pictures`;

Then this function deletes the image given the image name.

  deleteImageFile(filename) {

    const filepath = `${dirPicuturesTest}/${filename}`;

    RNFS.exists(filepath)
    .then( (result) => {
        console.log("file exists: ", result);

        if(result){
          return RNFS.unlink(filepath)
            .then(() => {
              console.log('FILE DELETED');
            })
            // `unlink` will throw an error, if the item to unlink does not exist
            .catch((err) => {
              console.log(err.message);
            });
        }

      })
      .catch((err) => {
        console.log(err.message);
      });
  }
5
acharlop On

I also used react-native-fs. But instead of recreating the file path I just used the file already given to me in my case by react-native-camera

const file = 'file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg'
const filePath = file.split('///').pop()  // removes leading file:///

RNFS.exists(filePath)
  .then((res) => {
    if (res) {
      RNFS.unlink(filePath)
        .then(() => console.log('FILE DELETED'))
    }
  }) 
1
Vraj Solanki On

Though it is already answered, for anyone tumbling upon the issue, you can also use react-native fetch-blob

RNFetchBlob.fs.unlink(path)
 .then(() => { ... })
 .catch((err) => { ... })