首页 > 解决方案 > 如何使用 moveFile react-native-fs

问题描述

我需要在 react native 应用程序上共享本地图像,使用 react-native share 和 react-native-fs。图像位于名为“图像”的根应用程序的本地文件夹中。如何分享这张图片。我是否需要将图像复制或移动到 temp 并使用该图像来获取绝对路径。

这是我的代码。rnfs.movefile 不起作用

getAssetFileAbsolutePath = async () => {
  const dest =
  `${RNFS.TemporaryDirectoryPath}${Math.random().toString(36)
   .substring( 
    .7)}.png`;
  const img = './images/page1.png';
  try {
    await RNFS.moveFile(img, dest);
    console.log("dobro", dest)
  } catch(err) {
    console.log("greska", err)
  } 
 }

我收到错误“page1.png”无法移动到“tmp”,因为前者不存在,或者包含后者的文件夹不存在。

标签: react-nativefilesystemsreact-native-fsmovefile

解决方案


使用rn-fetch blob和 react native share 首先查找图像的路径并将其转换为 base64。然后分享图片使用反应原生分享包

ShareFile(file) {
    let imagePath = null;
    RNFetchBlob.config({
        fileCache: true
    })
    .fetch("GET", file)
    // the image is now dowloaded to device's storage
    .then(resp => {
        // the image path you can use it directly with Image component
        imagePath = resp.path();
        return resp.readFile("base64");
    })
    .then(async base64Data => {
        var base64Data = `data:image/png;base64,` + base64Data;
        // here's base64 encoded image
        await Share.open({ url: base64Data });
        // remove the file from storage
        return fs.unlink(imagePath);
    });
}

推荐阅读