Cur*_*urt 53
您可以运行一些jQuery客户端验证来检查:
$(function(){
$("input[type='submit']").click(function(){
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length)>2){
alert("You can only upload a maximum of 2 files");
}
});
});?
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/Curt/u4NuH/
但请记住检查服务器端,因为客户端验证可以很容易地被绕过.
小智 8
$("#image").on("change", function() {
if ($("#image")[0].files.length > 2) {
alert("You can select only 2 images");
} else {
$("#imageUploadForm").submit();
}
});Run Code Online (Sandbox Code Playgroud)
如果文件数量大于 max_file_number,这应该可以工作并保护您的表单不被提交。
$(function() {
var // Define maximum number of files.
max_file_number = 3,
// Define your form id or class or just tag.
$form = $('form'),
// Define your upload field class or id or tag.
$file_upload = $('#image_upload', $form),
// Define your submit class or id or tag.
$button = $('.submit', $form);
// Disable submit button on page ready.
$button.prop('disabled', 'disabled');
$file_upload.on('change', function () {
var number_of_images = $(this)[0].files.length;
if (number_of_images > max_file_number) {
alert(`You can upload maximum ${max_file_number} files.`);
$(this).val('');
$button.prop('disabled', 'disabled');
} else {
$button.prop('disabled', false);
}
});
});
Run Code Online (Sandbox Code Playgroud)
JS的另一种可能解决方案
function onSelect(e) {
if (e.files.length > 5) {
alert("Only 5 files accepted.");
e.preventDefault();
}
}
Run Code Online (Sandbox Code Playgroud)