Applying javascript to check file size and extension

前端 未结 7 820
借酒劲吻你
借酒劲吻你 2021-01-05 00:40

here is my script. What I am trying to do is to trigger it using onchange event. But it seems does not work very well. I have tried edit here and there but still facing prob

相关标签:
7条回答
  • 2021-01-05 00:53
        <!DOCTYPE html>
            <html>
            <body>
    
            <p>When you submit the form, a function is triggered which alerts some text.</p>
    
            <form action="demo_form.asp" id="form">
              Enter name: <input type="file" name="fname" id="form_file" onchange=" return myFunction()">
              <input type="submit" value="Submit" id="submit">
            </form>
    
            <script>
            function myFunction() {
                 var file = document.getElementById("form_file");
                 var file_name = file.value;
                 var extension = file_name.split('.').pop().toLowerCase();
                 var size      = file.files[0].size;
                 var allowedFormats = ["jpeg", "jpg", "pdf", "tif"];
    
                  if(!(allowedFormats.indexOf(extension) > -1)){
                   alert("Enter a jpg/jpeg/pdf/tif file");
    
                   document.getElementById("submit").disabled = true;
                   return false;              
                  } else if( ((size/1024)/1024) > 15){
                     alert("Your file should be less than 15MB");
                     return false;
                  } else {
                   document.getElementById("submit").disabled = false;   
                  }
            }
            </script>
            </body>
            </html>
    
    0 讨论(0)
  • 2021-01-05 00:54

    you can used this code with file controller in html. any only pass parameter and see the output

       <script type="text/javascript">
    function AlertFilesize(cid,sz,a){
        var controllerID = cid;
        var fileSize = sz;
        var extation = a;
        if(window.ActiveXObject){
            var fso = new ActiveXObject("Scripting.FileSystemObject");
            var filepath = document.getElementById('fileInput').value;
            var thefile = fso.getFile(filepath);
            var sizeinbytes = thefile.size;
        }else{
            var sizeinbytes = document.getElementById('fileInput').files[0].size;
        }
        var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
        fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
        var fup = document.getElementById('fileInput');
        var fileName = fup.value;
        var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG")
        {   
            var fs = Math.round(fSize);
            if(fs < fileSize && fSExt[i] == extation)
            {
                alert("Image Successfully Uploaded");
                return true;}else{
                alert("Please enter the image size less then"+fileSize+extation);
                document.getElementById('fileInput').value='';
                return false;
                }
            }else{
            alert("Must be jpg and gif images ONLY");
            document.getElementById('fileInput').value='';
            return false;}
        }
    </script>
    <input id="fileInput" type="file" onchange="AlertFilesize(this.id,100,'KB');" />
    
    0 讨论(0)
  • 2021-01-05 01:00
    <script type="text/javascript">
    function setFileSize() {
            var fileEl = document.getElementById('<%=FileUpload1.ClientID%>');
            var fileSize = fileEl.files[0].size / 1024 / 1024;
            var fileName = fileEl.files[0].name;
            var dotPosition = fileName.lastIndexOf(".");
            var fileExt = fileName.substring(dotPosition);
            if (fileSize > 1) {
            fileEl.value = '';
                document.getElementById('<%=lblFileStatus.ClientID%>').innerHTML = 'File Should Be less Than 1MB';
                return false;
            }
    }
    


    0 讨论(0)
  • 2021-01-05 01:01

    Rather than relying on the elements them self you should use the given event to the function to get the file(s) that triggered the call to the callback function.

    Passing in the event will guarantee you that you are actually working with the current files that caused the function to be called.

    For example (I changed the variable name to make it more clear):

    ONLINE DEMO HERE

    /// pass in event 
    function checkFile(e) {
    
        /// get list of files
        var file_list = e.target.files;
    
        /// go through the list of files
        for (var i = 0, file; file = file_list[i]; i++) {
    
            var sFileName = file.name;
            var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
            var iFileSize = file.size;
            var iConvert = (file.size / 1048576).toFixed(2);
    
            /// OR together the accepted extensions and NOT it. Then OR the size cond.
            /// It's easier to see this way, but just a suggestion - no requirement.
            if (!(sFileExtension === "pdf" ||
                  sFileExtension === "doc" ||
                  sFileExtension === "docx") || iFileSize > 10485760) { /// 10 mb
                txt = "File type : " + sFileExtension + "\n\n";
                txt += "Size: " + iConvert + " MB \n\n";
                txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
                alert(txt);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-05 01:05

    This might help

    var file = document.getElementById("filex").files[0];
    var filename = file.name;
    
    var extSplit = filename.split('.');
    var extReverse = extSplit.reverse();
    var ext = extReverse[0];
    
    if(!ext === "mp4" || !ext === "flv"){
      alert('Accepted');
    } else {
      alert('Not accepted');
    }
    
    0 讨论(0)
  • 2021-01-05 01:05

    This is JavaScript onchange event base file size and type validation script, and it can be use in multiple input files

    <input type="file" onchange="checkFile(this)" class="form-control" name="doc_file[]">
    <script>
    function checkFile(item){
        var extension = $(item).val().split('.').pop().toLowerCase();
    // Create array with the files extensions that we wish to upload
        var validExtensions = ['jpeg', 'jpg', 'cdr', 'pdf', 'tiff'];
        //Check file extension in the array.if -1 that means the file extension is not in the list.
        if ($.inArray(extension, validExtensions) == -1) {
            $('#errormsg').text("Failed! Please upload jpg, jpeg, cdr, tiff, pdf file only.").show();
        // Clear fileuload control selected file
            $(item).replaceWith($(item).val('').clone(true));
        //Disable Submit Button
            $('#submit').prop('disabled', true);
        }
        else {
        // Check and restrict the file size to 32 KB.
            if ($(item).get(0).files[0].size > (20971520)) {
                $('#errormsg').text("Failed!! Max allowed file size is 20 MB").show();
            // Clear fileuload control selected file
                $(item).replaceWith($(item).val('').clone(true));
            //Disable Submit Button
                $('#submit').prop('disabled', true);
            }
            else {
            //Clear and Hide message span
                $('#errormsg').text('').hide();
            //Enable Submit Button
                $('#submit').prop('disabled', false);
            }
        }
    };
    </script>
    
    0 讨论(0)
提交回复
热议问题