1

複数のファイルアップローダーで閲覧中submitまたは閲覧する画像形式を検証したい。onchange

しかし、その後Googleとその後、私はJSスクリプトで複数の画像参照の検証を見つけることができません。HTML

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

2 に答える 2

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;
}
于 2012-12-29T12:57:19.893 に答える
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
    
于 2018-03-04T04:45:45.963 に答える