How To Get File Info Before Uploading in JavaScript

It is a very important thing for us to check the file info before uploading it to the server. So, in this tutorial, I will show you how to get file info before uploading in JavaScript. With this post, you gonna learn the following things

  1. Get the file name in JavaScript
  2. Get file type in JavaScript
  3. Get the file size in JavaScript
  4. File last modified date in JavaScript

Real Time Chat Application PHP With File Transfer System AJAX

Free Currency Converter PHP using Fixer io API

Get file info in JavaScript

To get the file info in JavaScript our first step is to create a file select input field.

So the HTML input field will be like this:

<input type="file" id="myfile" onchange="filedetails()"/>

Our input type should be “file”. Give an ID to it so that you can identify this easily in future. And we are going to call a function on change. Here filedetails() is the function name which we gonna call.

Thereafter, To get the file name in JavaScript. You need to use the below code:

document.getElementById('myfile').files[0].name

If you pick one file in the input field that means your first file having the index zero, the second file is having the index 1. Just select the file by document.getElementById(‘myfile’).files[0]
and then append .name to get the file name.

In the same way you can get the following informations regarding to a file.

document.getElementById('myfile').files[0].size

This will give you the file size. ( Get file size in JavaScript )

And finally,

document.getElementById('myfile').files[0].lastModifiedDate

This will give you the last modification date of the selected file. ( Get File Modified Date in JavaScript )

document.getElementById('myfile').files[0].type

This will give you the type of a file. ( Get the type of a file in JavaScript )

Get all info of a file in JavaScript

function filedetails(){
    var Name = document.getElementById('myfile').files[0].name;
    var Size = document.getElementById('myfile').files[0].size;
    var ModificationDate = document.getElementById('myfile').files[0].lastModifiedDate;
    var Type = document.getElementById('myfile').files[0].type;
    var output_file_informations = Name+"\n"+Size+"\n"+ModificationDate+"\n"+Type;
    alert(output_file_informations);
}

HTML5 Video Volume Controller in JavaScript with Slider

Leave a Reply

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