Error when moving file with react-native-fs, file already exist

870 views Asked by At

I am trying to move an image to the library using react-native-fs in iOS

const originalPath = "/private/var/mobile/Containers/Data/Application/7EB7B0CB-FCA8-49EE-843A-04BBB0B286B1/tmp/ReactNative/E70143FD-21A8-42AA-BFD2-A8FA45D7D93A.png"

const destinationPath = RNFS.LibraryDirectoryPath + "/kj3.jpg";

        RNFS.moveFile(screenShotPath, destinationPath).then((data) => {
            console.log(data)
        }).catch((err) => {
            throw err
        })

The destination path in this case is

/var/mobile/Containers/Data/Application/7EB7B0CB-FCA8-49EE-843A-04BBB0B286B1/Library/kj3.jpg

I get an error

Error: “E70143FD-21A8-42AA-BFD2-A8FA45D7D93A.png” couldn’t be moved to “Library” because an item with the same name already exists.

I also get the same error when I try to copy the file.

1

There are 1 answers

0
Max Cheung On

In iOS, image will not overwrite if already exists. Please try to console.log the screenShotPath and destinationPath to make sure the path are really different.

Below is a working solution shows that you can first check the file is it exists. If so, it will try to remove it first, then it will move the file as you want to prevent any exists error.

Hope it will help you!

RNFS.exists(path + filename)
                    .then(exists => {
                      if (exists) {
                        // If the image file exists, remove it
                        return RNFS.unlink(destinationPath);
                      } else {
                        // If the image file does not exist, do nothing
                        return Promise.resolve();
                      }
                    })
                    .then(() => {
                      // Move the image file to the new location
                      return RNFS.moveFile(screenShotPath, destinationPath);
                    })
                    .then(() => {
                      console.log('Image file moved successfully');
                    })
                    .catch(error => {
                      console.log('Error moving image file:', error);
                    });