我想验证图像格式期间submit
或onchange
将由多个文件上传器浏览。
但是之后Google
和之后我无法在JS
脚本中找到多个图像浏览验证.. 这是HTML
<input type="file" id='uploadImg' name='uploadImg[]' multiple >
<input id="imgaeupload" value="Submit" type="submit" name='uploadImage'/>
我想验证图像格式期间submit
或onchange
将由多个文件上传器浏览。
但是之后Google
和之后我无法在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中制作用于图像上传验证的通用函数
在 HTML 文件中
<input type="file" name="productImage_name[]" multiple="multiple" onchange="imageTest(this)">
在 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