web-dev-qa-db-ja.com

Reactネイティブファイル処理-画像を削除

写真をクリックするために react-native-camera を使用しています。状態で保存しているカメラからのデータに、「file:///storage/emulated/0/Pictures/IMG_20161228_021132.jpg」のようなファイルパスがあります。これを画像コンポーネント「Imagesource = {{uri:this.props.note.imagePath.path}}」を使用して画像を表示するためのソースとして使用でき、正しく表示されています。

次に、画像の削除機能を追加します。上記のパスを使用して電話でこの画像にアクセスし、電話から削除する方法を誰かが提案できますか?.

react-native-filesystem をチェックしましたが、このパスを渡すcheckIfFileExists関数を使用すると、ファイルが存在しないことがわかりました。何が悪いのかわからない。

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

8
Aman Agarwal

だから私は react-native-fs を使ってそれをすることができました

パスは次のように宣言する必要があります。

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

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

次に、この関数は、画像名を指定して画像を削除します。

  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
Aman Agarwal

すでに回答済みですが、問題に遭遇した人は、 react-native fetch-blob を使用することもできます。

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

react-native-fsも使用しました。しかし、ファイルパスを再作成する代わりに、私の場合は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
acharlop