How to get the size of a file in React

Last updated on Sep 16, 2022 by Suraj Sharma



In this tutorial, you will learn how you can get the size of an image file before you upload it to the server using React.js


This tutorial reuses the code from my tutorial on How to upload files in React.

To get the image file size in React, we will use the File object's size property, which returns the size of the file in bytes.


  event.target.files[0].size


Solution

import React from 'react';

const Form = () => {
  // a local state to store the currently selected file.
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleSubmit = (event) => {
    event.preventDefault()
    // check the tutorial on 
    // how to upload files in React to complete this function
  }

  const handleFileSelect = (event) => {
    const file = event.target.files[0]
    const size = file.size // it's in bytes
    console.log(size)
    //added a max file size limit of 100Kb
    if (size/1024 > 100) {
      alert("file size must not be greater than to 100Kb")
      return
    }
    setSelectedFile(event.target.files[0])
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileSelect} />
      <input type="submit" value="Upload File" />
    </form>
  )
};

export default Form;


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.