1、引入必要的css,js
<link rel="stylesheet" th:href="@{/resources/bootstrap/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/resources/awi/plugins/bootstrapvalidator/css/bootstrapValidator.min.css}">
<script th:src="@{/resources/awi/plugins/jQuery/jquery-2.2.3.min.js}"></script>
<script th:src="@{/resources/awi/plugins/bootstrapvalidator/js/bootstrapValidator.js}"></script>
2、对应的html
<div class="form-group">
<label class="col-xs-2 control-label">提交凭证</label>
<div class="col-xs-8">
<input type="file" class="hidden" name="voucherFile" id="voucherFile" οnchange="changepic('voucherFile')">
<img src="/front/img/head.jpg" style="width: 20%;height: 20%;" id="img" οnclick="getPicture('voucherFile')">
</div>
</div>
3、对应的js
initValidator();
function add() {
var bootstrapValidator = $('#reportForm').data('bootstrapValidator').validate();
if (bootstrapValidator.isValid()) {
var formdata = new FormData($("#reportForm")[0]);
form("/index/reportrecord/add",formdata,function (data) {
if (data.code == 0){
layer.msg("举报成功!",{time:2000},function () {
parent.layer.closeAll();
});
}else{
layer.msg("系统错误!",{time:2000},function () {
});
}
})
}
}
function initValidator() {
$('#reportForm').bootstrapValidator({
message: '输入值不满足要求',
excluded : [':disabled'],
verbose:false,//verbose为false表示一个字段的多个验证规则中,如果有一个验证不通过则继续去验证其他的字段 在0.5.2版本生效
fields: {
content: {
validators: {
notEmpty: {
message: '必填'
},
stringLength: {
max: 255,
message: '不能超过50位'
}
}
},
voucherFile: {
// group: '.col-xs-12',
trigger:"change",
validators: {
notEmpty: {
message: '凭证不能为空!'
},
file: {
extension: 'jpeg,jpg,png',
type: 'image/jpg,image/jpeg,image/png,',
maxSize: 2*1024*1024,
message: '允许上传的jpg、png且大小不能超过2M'
}
}
},
}
});
}
function changepic(voucherFile) {
$('#reportForm').data('bootstrapValidator').updateStatus("voucherFile", "NOT_VALIDATED", null );
$("#reportForm").data('bootstrapValidator').validateField('voucherFile');
if ($("#reportForm").data('bootstrapValidator').isValidField("voucherFile")){
var reads = new FileReader();
f = document.getElementById(voucherFile).files[0];
reads.readAsDataURL(f);
reads.onload = function (e) {
document.getElementById('img').src = this.result;
}
}
}
function getPicture(id) {
document.getElementById(id).click();
}