在multier文件上传器中验证JS中的多个图像格式


Validate multiple image format in JS in multipler file uploader

我想在submitonchange期间验证图像格式,这将通过多个文件加载器浏览。

但是在Google和SO之后,我无法在JS脚本中找到多个图像浏览验证。HTML

<input type="file" id='uploadImg' name='uploadImg[]' multiple >
<input id="imgaeupload" value="Submit" type="submit" name='uploadImage'/>

Files属性保存所选文件的列表,您可以遍历该列表并验证每个文件:

 function validate() {
    var uploadImg = document.getElementById('uploadImg');
    //uploadImg.files: FileList
    for (var i = 0; i < uploadImg.files.length; i++) {
       var f = uploadImg.files[i];
       if (!endsWith(f.name, 'jpg') && !endsWith(f.name,'png')) {
           alert(f.name + " is not a valid file!");
           return false;
       } else {
           return true;
       }
    }
}
function endsWith(str, suffix) {
   return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

在javascript中创建用于图像上传验证的通用函数

  1. HTML文件

    &lt;input type="file" name="productImage_name[]" multiple="multiple" onchange="imageTest(this)"&gt;
    
  2. Java Script文件

     function imageTest(field){
        var regex =  /('.jpg|'.jpeg|'.png|'.gif)$/i; // Check file type .jpg, .jpeg, .png, .gif etc.
     var target = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
     // target = http:  //  localhost  /  KapdaSearch/V1/Development/public/company
     var fileUploadPath = target.replace(/public.*/, "public/storage/images/"); // Here 1st parameter is regular expression 2nd is replace string with
     // fileUploadPath = http://localhost/KapdaSearch/V1/Development/public/storage/images/
    //alert(field.value); // It gives you fake path of file because of some security reason like C:/fakepath/abc.png
    // We need only file name so use field.files[0].name instead of field.value
    // Image validation when you select multiple images at once
     for(var i=0; i<field.files.length; i++){
    var fieldName = field.files[i].name; // Guess file name = xyz.png   
    var imgPath = fileUploadPath+fieldName; 
    // http://localhost/KapdaSearch/V1/Development/public/storage/images/xvz.png
    // Check file type is correct or not
    if(fieldName.match(regex)){
        // Check file already exist or not
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open('HEAD', imgPath, false);
        xmlhttp.send();
        if (xmlhttp.status == "404") {
            field.setCustomValidity('');
        } else {
            field.setCustomValidity('This '+fieldName+' is already exist. Change file name than upload..');
        }
    }
    else{
        field.setCustomValidity('This '+fieldName+' is invalid..');
    }
    } //End for loop
    } // End function