微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

存储在 react-native-fs 中的图像不显示 注意

如何解决存储在 react-native-fs 中的图像不显示 注意

我正在尝试使用 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); 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。