Find name, size, type, and last modified date time of a file in ReactJS

How to find the name, size, type, and modified date of a file in ReactJS:

In this tutorial, we will learn how to find the name, size, type, and modified date of a file in ReactJS. This is an important and commonly used feature in most applications. For example, if you have a file uploader in your web application, and you want to check the size and type of the file before you upload it, you can use the steps explained in this post.

I will write one react component that will show one file selector. You can click on that selector and select one file on your computer. Once the file is selected, it will print the name, size, type and modified date of that file on the console.

React.js component:

Create one file FileSelector.js with the following content:

import React from "react";

let handleChange = (e) => {
  var files = e.target.files;
  var filesArray = [].slice.call(files);
  filesArray.forEach((e) => {
    console.log(e.name);
    console.log(e.size);
    console.log(e.type);
    console.log(e.lastModified);
  });
};

let FileSelector = () => {
  return (
    <div>
      <h1>File Selector</h1>
      <input type="file" onChange={(e) => handleChange(e)} />
    </div>
  );
};

export default FileSelector;

It has one input component to pick a file from the system. It will call the handleChange function if any file is selected. You need to add this component to your main component. For example, if I add it to the App.js file, it will look as below:

import './App.css';
import FileSelector from './FileSelector';

function App() {
  return (
    <div className="App">
      <header className="App-header">
      <FileSelector/>        
      </header>
    </div>
  );
}

export default App;

Once it is added to your component, you will see one file selector:

ReactJS file selector

Click on the choose file button, select one file and it will print the details on the browser console.

The program is printing the following file properties:

  1. File.name: It returns the name of the file.
  2. File.size: It returns the size of the file(in bytes).
  3. File.type: It returns the MIME type of the file.
  4. File.lastModified: It returns the last modified time as number of milliseconds since Unix epoch. If the last modified time is not known, it returns the current date. You can convert this property to a Date object with the Date() constructor.
new Date(file.lastModified);

Reference :

  1. https://developer.mozilla.org/en-US/docs/Web/API/File

You might also like: