[javascript] JavaScript file upload size validation

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

This question is related to javascript validation file-upload

The answer is


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>

It's pretty simple.

            var 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;
            }

I ran across this question, and the one line of code I needed was hiding in big blocks of code.

Short answer: this.files[0].size

By the way, no JQuery needed.


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.


You can try this fineuploader

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


I made something like that:

_x000D_
_x000D_
$('#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')
}
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">
_x000D_
_x000D_
_x000D_


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


Using jquery:

<form action="upload" enctype="multipart/form-data" method="post">
                
    Upload image:
    <input id="image-file" type="file" name="file" />
    <input type="submit" value="Upload" />

    <script type="text/javascript">
        $('#image-file').bind('change', function() {
            alert('This file size is: ' + this.files[0].size/1024/1024 + "MiB");
        });
    </script>

</form>

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.


Works for Dynamic and Static File Element

Javascript Only Solution

_x000D_
_x000D_
function ValidateSize(file) {
        var FileSize = file.files[0].size / 1024 / 1024; // in MiB
        if (FileSize > 2) {
            alert('File size exceeds 2 MiB');
           // $(file).val(''); //for clearing with Jquery
        } else {

        }
    }
_x000D_
 <input onchange="ValidateSize(this)" type="file">
_x000D_
_x000D_
_x000D_


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.'
);

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.

<input type="file" id="fileinput" />
<script type="text/javascript">
  function readSingleFile(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 + " bytesn"
              + "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");
    }
  }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to file-upload

bootstrap 4 file input doesn't show the file name How to post a file from a form with Axios File Upload In Angular? How to set the max size of upload file The request was rejected because no multipart boundary was found in springboot Send multipart/form-data files with angular using $http File upload from <input type="file"> How to upload files in asp.net core? REST API - file (ie images) processing - best practices Angular - POST uploaded file