Home >>Javascript Programs >How to Get the size of a file with JavaScript

How to Get the size of a file with JavaScript

Get the size of a file with JavaScript

JavaScript can help you out easily to put restrictions on the file size. Sometimes user uploads big file to server, to avoid overloading your server with big files, you can easily write a JavaScript code to print the size of the file. So, in this article, we will learn how to code to get the size of a file with JavaScript.

Let's take an example:

<!DOCTYPE html>
		<meta charset="utf-8">
		<title>Javascript back demo</title>
        <input type="file"
               onchange="Filevalid()" /> 
       <p id="size"></p> 
    Filevalid = () => { 
        const fi = document.getElementById('file'); 
        // Check if any file is selected. 
        if (fi.files.length > 0) { 
            for (const i = 0; i <= fi.files.length - 1; i++) { 
                const fsize = fi.files.item(i).size; 
                const file = Math.round((fsize / 1024)); 
                // The size of the file. 
                if (file >= 4096) { 
                      "File too Big, please select a file less than 4mb"); 
                } else if (file < 2048) { 
                      "File too small, please select a file greater than 2mb"); 
                } else { 
                    document.getElementById('size').innerHTML = '<b>'
                    + file + '</b> KB'; 
Output: Get File size