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

时间:2012-12-29 12:24:56

标签: php javascript jquery html

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

但是在Google之后,我在JS脚本中找不到多个图片浏览验证。 这是HTML

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

2 个答案:

答案 0 :(得分:5)

文件上传元素的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;
}

答案 1 :(得分:0)

在javascript中制作常用功能以进行图片上传验证

  1. 在HTML文件中

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

     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