Validate File size before upload

后端 未结 3 1711
野性不改
野性不改 2021-01-06 19:14

I need to validate the file which is to be uploaded to the server. The validation must be done before uploading it. i.e., validation completed at client side. This task shou

3条回答
  •  爱一瞬间的悲伤
    2021-01-06 19:48

    When it comes for a browser that supports HTML 5, it can be easily achieved with simple javascript:

    Html Syntax

    
    

    Javascript syntax

    //gets the element by its id
    var myFile = document.getElementById('myFile');
    
    //binds to onchange event of the input field
    myFile.addEventListener('change', function() {
      //this.files[0].size gets the size of your file.
      alert(this.files[0].size);
    
    });
    

    BUT, when it comes to an older browser (and we are all looking to you, Internet Explorer), the only way to do that on the client side is by using ActiveX:

    var myFile = document.getElementById('myFile');
    
    var myFSO = new ActiveXObject("Scripting.FileSystemObject");
    var filepath = myfile.file.value;
    var thefile = myFSO.getFile(filepath);
    var size = thefile.size;
        alert(size + " bytes");
    

提交回复
热议问题