3

I'm having difficulty fetching an image from a url, storing the image on a device, and opening/viewing it successfully.

I am able to fetch the image successfully (I believe)

I transform the image into base64 using Buffer (npm buffer) and save it to the device using react-native-fs. I'm not sure the Buffer transformation is needed. I can stat the image and everything looks fine. When I use a FileManager application I downloaded and I click on the file the image is blank.

let response = await axios.request({
    url: imgUrl
  });
let idxStart = imgUrl.lastIndexOf('/');
let idxEnd = imgUrl.lastIndexOf('.');
let filename = imgUrl.substring(idxStart + 1, idxEnd) + '.jpg';
let path = RNFS.DocumentDirectoryPath + `/${filename}`
let base64data = new Buffer(response.data).toString('base64');

RNFS.writeFile(RNFS.PicturesDirectoryPath + '/' + filename, base64data, 'base64').then(() => {

    RNFS.stat(path).then(info => {
      console.log(info);
    });

    RNFS.readFile(RNFS.PicturesDirectoryPath + '/' + filename, 'base64').then(data => {
      // console.log('data:', data);
    });

  } ,error => {
    console.log('error writing file:', error)
}).catch(error => { console.log('error:', error)});

If anybody could provide a simple working example that'd be AWESOME!

jackfrost
  • 31
  • 2

0 Answers0