JavaScript file upload size validation

后端 未结 13 2174
眼角桃花
眼角桃花 2020-11-22 00:23

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

相关标签:
13条回答
  • 2020-11-22 01:15

    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. You file size is: ' + numb +' MB');
    } 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">

    0 讨论(0)
  • 2020-11-22 01:15

    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");
        }
      }
    
    0 讨论(0)
  • 2020-11-22 01:16

    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>
    
    0 讨论(0)
  • 2020-11-22 01:19

    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.

    0 讨论(0)
  • 2020-11-22 01:19

    You can try this fineuploader

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

    0 讨论(0)
  • 2020-11-22 01:20

    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.

    0 讨论(0)
提交回复
热议问题