首页 > 解决方案 > 如何在 react-native 中获取绝对图像路径?

问题描述

我需要根据音频和图像创建视频。我在我的应用文件夹中保存了一张图片/src/img/test.jpg。要创建视频,我需要一个绝对图像路径。

我试过了react-native-fs。这是一些代码,我试图将图像从 src 路径复制到 DocumentDirectoryPath。

const dest = `${RNFS.DocumentDirectoryPath}/test.jpg`;
const path =  'src/img/test.jpg'

RNFS.copyFile(path, dest)
  .then(() => FileViewer.open(dest))
    .then(() => {
      RNFS.readDir(RNFS.DocumentDirectoryPath) 
      .then((result) => {
        console.log('GOT RESULT', result);
      })
    })
  .catch(_err => {
    console.log(_err);
});

我得到了错误: Error: The file “test.jpg” couldn’t be opened because there is no such file.

标签: iosreact-native

解决方案


你无法访问

const path =  'src/img/test.jpg'

在运行时,因为它捆绑在您的应用程序中

尝试这个 :

const dest = `${RNFS.DocumentDirectoryPath}/test.jpg`;
const img =  require('src/img/test.jpg');

RNFS.writeFile(dest, img, "base64")
  .then(() => FileViewer.open(dest))
  .then(() => {
     RNFS.readDir(RNFS.DocumentDirectoryPath) 
  .then((result) => {
    console.log('GOT RESULT', result);
     })
  })
  .catch(_err => {
     console.log(_err);
  });

推荐阅读