React Native file handling - delete image

I am using react-native-camera to click on the images. I get the file path, for example: "file: ///storage/emulated/0/Pictures/IMG_20161228_021132.jpg" in the data from the camera, which I keep in state. I can use this as a source to display the image using the component "Image Source = {{uri: this.props.note.imagePath.path}}" and it displays correctly.

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

I checked react-native-filesystem , but when I used the checkIfFileExists function that goes along this path, I realized that the file does not 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 debug snapshot

+4
source share
3 answers

So, I was able to do this using react-native-fs

The path should be declared as follows:

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

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

This function then deletes the image with 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);
      });
  }
+3
source

I also used react-native-fs. But instead of re-creating the file path, I just used the file already provided to me in my case,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
source

, , , response-native fetch-blob

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

Source: https://habr.com/ru/post/1665041/


All Articles