JavaScript file upload size validation
Asked Answered
C

15

368

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

Catechol answered 15/9, 2010 at 12:58 Comment(1)
I just ran into a similar problem using Chrome. I just closed the tab and opened a new one.Farinaceous
E
433

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.

Elianore answered 15/9, 2010 at 13:5 Comment(1)
+1 for the "all client-side limits (and other validations) can be circumvented". This is just as true for "native"/"compiled" database frontend applications. And don't put the database access passwords in your compiled code, not even "encrypted" (with a password that is in the code too - just saw this recently).Mimi
D
145

Using jquery:

$('#image-file').on('change', function() {
  console.log('This file size is: ' + this.files[0].size / 1024 / 1024 + "MiB");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form action="upload" enctype="multipart/form-data" method="post">

  Upload image:
  <input id="image-file" type="file" name="file" />
  <input type="submit" value="Upload" />


</form>
Deterioration answered 6/11, 2012 at 11:21 Comment(3)
@ipd, any chance of an IE8 fallback? (I'm hating myself for even mentioning IE)Effort
This one works grate but does it works for multiple files also?Arsenite
It should be MiB if you calculate to the base of 1024.Tobe
P
139

Works for Dynamic and Static File Element

Javascript Only Solution

function validateSize(input) {
  const fileSize = input.files[0].size / 1024 / 1024; // in MiB
  if (fileSize > 2) {
    alert('File size exceeds 2 MiB');
    // $(file).val(''); //for clearing with Jquery
  } else {
    // Proceed further
  }
}
<input onchange="validateSize(this)" type="file">
Portion answered 12/6, 2017 at 17:24 Comment(5)
Nice Answer. I was having the same problem but your solution worked for me :)Quicksand
NB OP edited the post so the code is now correct, using the size propertyHydatid
Thanks for the answer I was almost doing the same but with one change. $(obj).files[0].size/1024/1024; But changed it to obj.files[0].size/1024/1024;Nunatak
Is there a way for extend this for width and height validation? (leaving a "file" as the starting point and assuming it refers to an image)Emblazonment
@Emblazonment I think you could read the file with the help of canvas and get it's height and width here itself.Portion
A
30

It's pretty simple.

const oFile = document.getElementById("fileUpload").files[0]; // <input type="file" id="fileUpload" accept=".jpg,.png,.gif,.jpeg"/>

if (oFile.size > 2097152) // 2 MiB for bytes.
{
  alert("File size must under 2MiB!");
  return;
}
Antiphlogistic answered 22/4, 2016 at 14:37 Comment(0)
P
15

If you're using jQuery Validation, you could write something like this:

$.validator.addMethod(
  "maxfilesize",
  function (value, element) {
    if (this.optional(element) || ! element.files || ! element.files[0]) {
      return true;
    } else {
      return element.files[0].size <= 1024 * 1024 * 2;
    }
  },
  'The file size can not exceed 2MiB.'
);
Peoples answered 29/4, 2013 at 9:10 Comment(0)
D
14

No Yes, using the File API in newer browsers. See TJ's answer for details.

If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.

The SWFUpload Features Demo shows how the file_size_limit setting works.

Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.

Distinctly answered 15/9, 2010 at 13:3 Comment(0)
T
14

I made something like that:

$('#image-file').on('change', function() {
  var numb = $(this)[0].files[0].size / 1024 / 1024;
  numb = numb.toFixed(2);
  if (numb > 2) {
    alert('to big, maximum is 2MiB. You file size is: ' + numb + ' MiB');
  } else {
    alert('it okey, your file has ' + numb + 'MiB')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">
Tman answered 30/8, 2018 at 21:55 Comment(1)
This says javascript, JQuery is not in the tagsPoff
O
11

Even though the question is answered, I wanted to post my answer. Might come handy to future viewers.You can use it like in the following code.

document.getElementById("fileinput").addEventListener("change",function(evt) {
  //Retrieve the first (and only!) File from the FileList object
  var f = evt.target.files[0];
  if (f) {
    var r = new FileReader();
    r.onload = function(e) {
      var contents = e.target.result;
      alert("Got the file\n" +
        "name: " + f.name + "\n" +
        "type: " + f.type + "\n" +
        "size: " + f.size + " bytes\n" +
        "starts with: " + contents.substr(1, contents.indexOf("\n"))
      );
      if (f.size > 5242880) {
        alert('File size Greater then 5MiB!');
      }


    }
    r.readAsText(f);
  } else {
    alert("Failed to load file");
  }
})
<input type="file" id="fileinput" />
Onitaonlooker answered 1/6, 2016 at 6:47 Comment(1)
upvoted just because you made me save 5 minutes of calculating how many bytes 5 MB is ;-)Monstrance
G
3

I use one main Javascript function that I had found at Mozilla Developer Network site https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications, along with another function with AJAX and changed according to my needs. It receives a document element id regarding the place in my html code where I want to write the file size.

<Javascript>

function updateSize(elementId) {
    var nBytes = 0,
    oFiles = document.getElementById(elementId).files,
    nFiles = oFiles.length;

    for (var nFileId = 0; nFileId < nFiles; nFileId++) {
        nBytes += oFiles[nFileId].size;
    }
    var sOutput = nBytes + " bytes";
    // optional code for multiples approximation
    for (var aMultiples = ["K", "M", "G", "T", "P", "E", "Z", "Y"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
        sOutput = " (" + nApprox.toFixed(3) + aMultiples[nMultiple] + ")";
    }

    return sOutput;
}
</Javascript>

<HTML>
<input type="file" id="inputFileUpload" onchange="uploadFuncWithAJAX(this.value);" size="25">
</HTML>

<Javascript with XMLHttpRequest>
document.getElementById('spanFileSizeText').innerHTML=updateSize("inputFileUpload");
</XMLHttpRequest>

Cheers

Glassy answered 26/7, 2013 at 18:22 Comment(0)
R
3

JQuery example provided in this thread was extremely outdated, and google wasn't helpful at all so here is my revision:

<script type="text/javascript">
  $('#image-file').on('change', function() {
    console.log($(this)[0].files[0].name+' file size is: ' + $(this)[0].files[0].size/1024/1024 + 'Mb');
  });
</script>
Rivulet answered 10/8, 2017 at 17:48 Comment(0)
K
3

Short and sweet: this.files[0].size

Kimbell answered 8/9, 2020 at 6:46 Comment(0)
A
2

I use this script to validate file type and size

 var _validFilejpeg = [".jpeg", ".jpg", ".bmp", ".pdf"];

    function validateForSize(oInput, minSize, maxSizejpeg) {
        //if there is a need of specifying any other type, just add that particular type in var  _validFilejpeg
        if (oInput.type == "file") {
            var sFileName = oInput.value;
            if (sFileName.length > 0) {
                var blnValid = false;
                for (var j = 0; j < _validFilejpeg.length; j++) {
                    var sCurExtension = _validFilejpeg[j];
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length)
                        .toLowerCase() == sCurExtension.toLowerCase()) {
                        blnValid = true;
                        break;
                    }
                }

                if (!blnValid) {
                    alert("Sorry, this file is invalid, allowed extension is: " + _validFilejpeg.join(", "));
                    oInput.value = "";
                    return false;
                }
            }
        }

        fileSizeValidatejpeg(oInput, minSize, maxSizejpeg);
    }

    function fileSizeValidatejpeg(fdata, minSize, maxSizejpeg) {
        if (fdata.files && fdata.files[0]) {
            var fsize = fdata.files[0].size /1024; //The files property of an input element returns a FileList. fdata is an input element,fdata.files[0] returns a File object at the index 0.
            //alert(fsize)
            if (fsize > maxSizejpeg || fsize < minSize) {
                alert('This file size is: ' + fsize.toFixed(2) +
                    "KB. Files should be in " + (minSize) + " to " + (maxSizejpeg) + " KB ");
                fdata.value = ""; //so that the file name is not displayed on the side of the choose file button
                return false;
            } else {
                console.log("");
            }
        }
    }
<input type="file"  onchange="validateForSize(this,10,5000);" >
Amalekite answered 15/1, 2022 at 13:32 Comment(0)
V
1

You can try this fineuploader

It works fine under IE6(and above), Chrome or Firefox

Verbena answered 20/9, 2012 at 8:47 Comment(1)
Fine Uploader is not able to validate file size in IE9 and older as the do not support the File API is not supported. IE10 is the first version of Internet Explorer that supports the File API.Oodles
T
-2

If you set the Ie 'Document Mode' to 'Standards' you can use the simple javascript 'size' method to get the uploaded file's size.

Set the Ie 'Document Mode' to 'Standards':

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

Than, use the 'size' javascript method to get the uploaded file's size:

<script type="text/javascript">
    var uploadedFile = document.getElementById('imageUpload');
    var fileSize = uploadedFile.files[0].size;
    alert(fileSize); 
</script>

It works for me.

Throwback answered 31/7, 2013 at 13:54 Comment(1)
This will not work in IE9 or older, no matter what meta tags you add.Oodles
S
-2

Simple way is

const myFile = document.getElementById("fileUpload").files[0]; 
            if (myFIle.size > 2097152) // 2 MiB for bytes.
            {
                alert("File size must under 2MiB!");
                return;
            }

Surd answered 20/4, 2021 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.