DEV Community

Cover image for How to gets uploaded image Metadata on the front-end
Alexey Lysenko
Alexey Lysenko

Posted on

How to gets uploaded image Metadata on the front-end

Quite often when we implement uploading images, will be great to have the opportunity somehow to get image metadata (with, height, fileSize, name ..) in the front-end directly

Example of the input, with uploading the image file:

<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" onChange={ (e) => handleChange(e.target.files) } /> 
Enter fullscreen mode Exit fullscreen mode

to get the name, file size and extension of the uploaded file:

const file = e.target.files[0] const { name } = file const fileExtension = name.split('.').pop() const fileSize = file.size 
Enter fullscreen mode Exit fullscreen mode

in the case, if needs to get local URL thats used to show render uploaded image:

const localUrl = URL.createObjectURL(file) 
Enter fullscreen mode Exit fullscreen mode

To get width, height, of the uploaded image use new FileReader() with image.decode() method:

var reader = new FileReader() reader.onload = async (e: any) => { let image = new Image() image.src = e.target.result await image.decode() // now we can: const width = image.width const height = image.height } reader.readAsDataURL(file) 
Enter fullscreen mode Exit fullscreen mode

this is async logic so a better way to use it in a project is to wrap it up with a new Promise, I use the async function wrapper to get all needed metadata:

// Function takes single uploaded img file, and returns width, height, fileSize and fileExtension export const getImageMeta = async ( file: File ): Promise<{ width: number, height: number, fileSize: number, fileExtension: string, localUrl: string, }> => { const { name } = file const fileExtension = name.split('.').pop() const localUrl = URL.createObjectURL(file) // reading a file to get height and width async function getImageParams(file: File) { return new Promise((resolve, reject) => { var reader = new FileReader() reader.onload = async (e: any) => { var image = new Image() image.src = e.target.result await image.decode() resolve({ width: image.width, height: image.height }) } reader.readAsDataURL(file) }) } const { width, height } = await getImageParams(file) return { width, height, fileSize: file.size, fileExtension, localUrl } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
nextdev profile image
Next Dev

Thanks

Collapse
 
chris_silkey_ac626c3383b6 profile image
Chris Silkey

I was hoping we could get the file's timestamp?