当前位置 : 首页 » 互动问答 » 正文

JavaScript file upload size validation

分类 : 互动问答 | 发布时间 : 2010-09-15 20:58:42 | 评论 : 12 | 浏览 : 372880 | 喜欢 : 211

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

回答(12)

  • 1楼
  • Yes, there's a new feature from the W3C that's supported by some modern browsers, the File API. It can be used for this purpose, and it's easy to test whether it's supported and fall back (if necessary) to another mechanism if it isn't.

    Here's a complete example:

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Show File Data</title>
    <style type='text/css'>
    body {
        font-family: sans-serif;
    }
    </style>
    <script type='text/javascript'>
    function showFileSize() {
        var input, file;
    
        // (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) {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }
    
        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
        }
    }
    
    function bodyAppend(tagName, innerHTML) {
        var elm;
    
        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }
    </script>
    </head>
    <body>
    <form action='#' onsubmit="return false;">
    <input type='file' id='fileinput'>
    <input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
    </form>
    </body>
    </html>
    

    And here it is in action. Try that with a recent version of Chrome or Firefox.


    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.

  • 2楼
  • 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 + "MB");
            });
        </script>
    
    </form>
    
  • 3楼
  • Works for Dynamic and Static File Element

    Javascript Only Solution

    function ValidateSize(file) {
            var FileSize = file.files[0].size / 1024 / 1024; // in MB
            if (FileSize > 2) {
                alert('File size exceeds 2 MB');
               // $(file).val(''); //for clearing with Jquery
            } else {
    
            }
        }
     <input onchange="ValidateSize(this)" type="file">

  • 4楼
  • 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.

  • 5楼
  • 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 2MB.'
    );
    
  • 6楼
  • 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 mb for bytes.
                {
                    alert("File size must under 2mb!");
                    return;
                }
    
  • 7楼
  • 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

  • 8楼
  • 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 5MB!');
                    }
    
    
          }
          r.readAsText(f);
        } else { 
          alert("Failed to load file");
        }
      }
    
  • 9楼
  • 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>
    
  • 10楼
  • You can try this fineuploader

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

  • 11楼
  • 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 2MB');
    } else {
    alert('it okey, your file has ' + numb + 'MB')
    }
            });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <input type="file" id="image-file">

  • 12楼
  • 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.

相关阅读:

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How do I replace a character at a particular index in JavaScript?

JavaScript file upload size validation

JavaScript file upload size validation

JavaScript file upload size validation