Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript file upload size validation

Is there any way to check file size before uploading it using JavaScript?

like image 228
ArK Avatar asked Sep 15 '10 12:09

ArK


People also ask

How to check image size before upload in JavaScript?

To check image width and height before upload with JavaScript, we can get the dimensions by assigning the image data string to the src property of an img element. const reader = new FileReader(); reader. readAsDataURL(fileUpload. files[0]); reader.

How do I limit the upload file size in HTML?

size > 2097152){ alert("File is too big!"); this. value = ""; }; }; This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.


1 Answers

Yes, you can use the File API for this.

Here's a complete example (see comments):

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {     // (Can't use `typeof FileReader === "function"` because apparently it     // comes back as "object" on some browsers. So just see if it's there     // at all.)     if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal         console.log("The file API isn't supported on this browser yet.");         return;     }      var input = document.getElementById('fileinput');     if (!input.files) { // This is VERY unlikely, browser support is near-universal         console.error("This 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); }
body {     font-family: sans-serif; }
<form action='#' onsubmit="return false;"> <input type='file' id='fileinput'> <input type='button' id='btnLoad' value='Load'> </form>

Slightly off-topic, but: Note that client-side validation is no substitute for server-side validation. Client-side validation is purely to make it possible to provide a nicer user experience. For instance, if you don't allow uploading a file more than 5MB, you could use client-side validation to check that the file the user has chosen isn't more than 5MB in size and give them a nice friendly message if it is (so they don't spend all that time uploading only to get the result thrown away at the server), but you must also enforce that limit at the server, as all client-side limits (and other validations) can be circumvented.

like image 162
T.J. Crowder Avatar answered Sep 23 '22 13:09

T.J. Crowder