问题描述
我正在尝试使用 react native 和 react-native-fs 库将图像保存到文档目录(而不是缓存),但我得到了一张空白照片。
const localPath = (image) => {
console.log("Cache directory path is ",image)
const fileName = image.split('/').pop();
console.log('Filename is ',fileName)
const newPath = 'file://' + RNFS.DocumentDirectoryPath + '/' + fileName;
console.log(newPath)
// write the file
RNFS.writeFile(newPath,image,'base64')
.then((success) => {
console.log('IMG WRITTEN!');
console.log(newPath)
})
.catch((err) => {
console.log(err.message);
});
return newPath
}
所以我想用这个 newPath
<Image style={styles.image} source={{ uri: newPath }} />
但是出现一张空白照片.....如果我通过原始路径,则显示照片。
解决方法
如果 image
是文件的路径,只需使用 copyFile 方法
const localPath = (image) => {
console.log('Cache directory path is ',image)
const fileName = image.split('/').pop();
console.log('Filename is ',fileName)
const newPath = `${RNFS.DocumentDirectoryPath}/${fileName}`; // You don't really need the `'file://` prefix
console.log(newPath);
// COPY the file
RNFS.copyFile(image,newPath)
.then((success) => {
console.log('IMG COPIED!');
console.log(newPath);
})
.catch((err) => {
console.log(err.message);
});
return newPath
}
还有一个 moveFile 可以用来移动文件而不是复制
writeFile
用于将内容写入文件
注意
您用来复制图像并返回 newPath
的函数不是异步的 - 它会立即返回 newPath
- 可能在图像被复制到文档目录之前 - 这可能会导致问题如果 <Image>
在文件实际存在之前尝试加载它。
我只会在实际复制图像后返回 newPath
const localPath = async (image) => {
const newPath = `${RNFS.DocumentDirectoryPath}/${fileName}`;
await RNFS.copyFile(image,newPath);
return newPath;
}
// usage
const uri = await localPath(image);