Easy utility to handle compression when uploading files on mobile network

In a recent project I was working on, we needed to upload several images from a mobile web app. With the current smart phone camera advancements, these images have become rather large. With the iPhone 14 Pro you're even able to take RAW images.

When testing our uploads on poor mobile connections, we witnessed upload times north of 30 seconds for 3-4 images. Some users even complained, assuming that the application had timed out. We knew we had to fix this.

After some research, we found this very neat library browser-image-compression. We did, however, find that sometimes the image compression would fail. We came up with a simple function to compress the image, or return the original - like so:

const COMPRESSION_OPTIONS = {
  maxSizeMB: 1,
  maxWidthOrHeight: 1920,
  useWebWorker: true,
}

const compress = async (file: File): Promise<File> => {
  return new Promise(async (resolve) => {
    try {
      // Attempt to compress the image
      const compressedImage = await imageCompression(file, COMPRESSION_OPTIONS)
      resolve(compressedImage)
    } catch (e) {
      // If we fail, just return the old image
      resolve(file)
    }
  })
}

Pretty simple, right? We are able to set the max size of each file and other additional meta fields. Now when we use our image drop-zone we simply map over all the images to get our newly generated images!

const compressedImages = await Promise.allSettled(images.map(compress))

Stay up to date

Get notified when I publish something new, and unsubscribe at any time.