JS File Upload Size Validation

JS File Upload Size Validation

Many websites allow users to upload files that are text, images or other formats. Often most of these files are validated at server side but it is also good to check file size before it is uploaded on client side itself, and show relevant messages in case the uploaded file does not meet your website’s requirements. You can easily do this using JavaScript. In this article, we will learn how to do JS file upload size validation.


JS File Upload Size Validation

You can easily validate uploaded files using File API in web browsers. First we create an HTML form for file upload.

<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Upload'>
</form>

You can do file size validation using plain JavaScript or using third-party libraries like jQuery. We will learn both these methods.

1. Using JavaScript

Here is the code snippet to validate file size before uploading it.

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {

    if (!window.FileReader) { 
        console.log("The file API isn't supported on this browser yet.");
        return;
    }

    var input = document.getElementById('fileinput');
    if (!input.files) { 
        console.error("Browser doesn't seem to support the `files` property of file inputs.");
    } else if (!input.files[0]) {
        addPara("Please select a file before clicking 'Load'");
    } else {
        var file = input.files[0];
        addPara("File " + file.name + " is " + file.size + " bytes in size");
    }
});

function addPara(text) {
    var p = document.createElement("p");
    p.textContent = text;
    document.body.appendChild(p);
}

In the above code, we first check if File API is supported in browser. It is supported by almost every web browser and you can remove this piece of code if you want to.

Next, we get a hold of file input element in HTML form using getElementById() function. We do a couple of validations such as support for files property as well as whether the user has selected file before clicking upload button. Lastly, we check the file size. The uploaded files are stored in array called files of file input element. We check size property of the first element of this array file[0] and display its size in bytes. You can exit if the file exceeds a specific file size. To do this, just add return false after the validation. Here is an example to prevent upload if file size > 1Mb.

{
        var file = input.files[0];
        addPara("File " + file.name + " is " + file.size + " bytes in size");
        if(file.size> 1000000){
          return false;
        }
    }

2. Using jQuery

First, make sure you have imported jQuery library on your page.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Here is the code that is triggered whenever a file is uploaded on web page.

$('#fileinput').on('change', function() {
  console.log('This file size is: ' + this.files[0].size / 1024 / 1024 + "MiB");
});

For file input element, its uploaded files are stored in files array. We use this.files[0].size to get the file size of uploaded file, in bytes. We divide it by 1024*1024 to get result in Mb.

In this article, we have learnt a couple of easy ways to check file size before uploading it, using JavaScript. Client Side validations are useful to quickly show error messages, before even starting file upload, instead of waiting for file to be uploaded before showing response.

Please note, although we have shown how to check file size before uploading at client side, you must also validate it on server side, because client side validations can be overcome sometimes.

Also read:

How to Print Contents of Div in JavaScript
How to Check if Web Page is Loaded in IFrame or Web Browser
How to Detect Internet Connection is Offline in JS
How to Remove All Child Elements of DOM in JS
How to Check if Variable Exists or is Undefined in JS

Leave a Reply

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