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

Published by admin on

ReactJS find file name, size, type and modified date

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

In this tutorial, we will learn how to find the name of a file, the size, type, and modified data 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 before making any upload request to your server.

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. Then, we will print the name, size, type and modified date of that file on the console.

React.js component :

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.lastModifiedDate);
  });
};

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

export default FileSelector;

Put this component in a javascript file and import it in your main component. You will see one file selector like below :

ReactJS file selector

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

We are using one loop and 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.lastModifiedDate : It returns one Date object of the last modified time of the file.

You can also use lastModified

property to read the last modified UNIX time for that file, i.e. time in milliseconds since Jan 1st, 1970, midnight.

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

Categories: reactjs

1 Comment

chandjen · March 25, 2020 at 10:17 am

file.type doesn’t return MIME type of “docx” and “doc” files.. is there any work around to get that ?

Leave a Reply

Your email address will not be published. Required fields are marked *