react-nativereact-native-fs

ReactImageView: Image source "/storage/emulated/0/Download/UAC/forecasts/Salt_Lake/danger.png" doesn't exist. Even though I can verify it does exist


React Native Image

<Image source={{uri: imagePath}}/>

ReactImageView: Image source "/storage/emulated/0/Download/UAC/forecasts/Salt_Lake/danger.png" doesn't exist" even though it does in the android emulator.

Here is how I write the file

 let image = await axios.get(
          `https://PATH TO EXTERNAL SOURCE`,
          {
            params: {
              AccessKey: '',
            },
          },
        );
        let path = `${RNFS.DownloadDirectoryPath}/${center}/forecasts/${region}/`;
        path = path.replace(/ /g, '_');
        console.log(path);

        await RNFS.mkdir(path);

        await RNFS.writeFile(path + '/danger.png', image.data, 'base64');

I verified it by doing adb shell and cd-ing until I found the file I am looking for. These files clearly exists but for some reason the Image cannot find them.terminal screenshot


Solution

  • When using a local file path, you need to prefix the path with file://

    Here's an example of how you can update your code to include the file:// prefix and use proper URI encoding:

    async function downloadAndSaveImage(center, region) {
      try {
        let image = await axios.get(
          `https://PATH TO EXTERNAL SOURCE`,
          {
            params: {
              AccessKey: '',
            },
            responseType: 'arraybuffer',
          }
        );
    
        let path = `${RNFS.DownloadDirectoryPath}/${center}/forecasts/${region}/`;
        path = path.replace(/ /g, '_');
        console.log(path);
    
        await RNFS.mkdir(path);
    
        const imagePath = path + '/danger.png';
        await RNFS.writeFile(imagePath, image.data, 'base64');
    
        return `file://${imagePath}`;
      } catch (error) {
        console.error('Error downloading or saving the image:', error);
      }
    }
    

    Hope it helps to you :)