Corrupted Cached Images

  1. SDK Version: 40.0
  2. Platforms: Android/IOS

Hi everyone!

I’m implementing an algorithm to cache images using the expo-file-system library, but sometimes the images end up being corrupted, with a gray background (as you can see in the attached screenshots in the end).

To be honest, I just adapted what Ben Awad did here. You can see my code here:

The shorthash code comes from the shorthash library
And I use the “cacheFile” function inside an useEffect, like this:

Somethimes it works well, sometimes I get images like these:


Any ideas on what might be happening?

Looks like some images didn’t download properly. What I usually do is, checking if the file exists in the cache directory but also if the size makes sense.

FileSystem return more than exists or size. Check here: FileSystem - Expo Documentation

Also, do not add any ‘await’ directly in useEffect(). Do it this way:

import * as FileSystem from "expo-file-system";
import md5 from "md5";

let ImgUri = null;
useEffect(() => {    
      const DownLoadImage = async () => {   
           const img = 'http://example.com';
           const fileUri = FileSystem.cacheDirectory + md5(img) + ".jpg";
           const info = await FileSystem.getInfoAsync(fileUri);
           if (info.exists && info.size > 300) {
                ImgUri = fileUri;
           } else {
                await FileSystem.downloadAsync(img, fileUri);
                ImgUri = source.source.uri;
           }      
      }
      DownLoadImage();
},[]);

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.