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:
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:
File.name
: It returns the name of the file.File.size
: It returns the size of the file(in bytes).File.type
: It returns the MIME type of the file.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 aDate
object with theDate()
constructor.
new Date(file.lastModified);
Reference :
You might also like:
- How to create your first reactjs app using create-react-app
- What are Components in Reactjs and how to use these components
- How to add Material-UI to an existing Reactjs app
- Box component in material UI reactjs library
- Container component in Reactjs material-ui library
- How to open a link in a new tab in Reactjs