使用react-native-fs移动文件时出错,文件已存在

92dk7w1h  于 2023-03-24  发布在  React
关注(0)|答案(1)|浏览(177)

我尝试在iOS中使用react-native-fs将映像移动到库中

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
        })

本例中的目标路径为

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

我收到错误

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

我也得到了同样的错误,当我试图复制文件。

vybvopom

vybvopom1#

在iOS中,如果图像已经存在,则不会覆盖。请尝试console.log screenShotPath和destinationPath,以确保路径确实不同。
下面是一个工作解决方案,显示您可以首先检查文件是否存在。如果是这样,它将首先尝试删除它,然后它将移动文件,因为你想防止任何存在错误。
希望对你有帮助!

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);
                    });

相关问题