使用三种插件
uploadImg.min.css
uploadImg.min.js
CompressImgUpload.js
class = "uploadImg"
<form id="brandForm" class="form-horizontal" enctype="multipart/form-data"> <div class="input-group"> <!--编号id--> <input type="hidden" name="id" id="id"/> </div> <div class="form-group"> <label class="col-sm-3 control-label">名称</label> <div class="col-sm-8"> <input type="text" class="form-control" onkeyup="this.value=this.value.replace(/\s/g,‘‘)" name="name" id="name" placeholder=""/> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">说明</label> <div class="col-sm-8"> <textarea name="introduce" rows="5" class="form-control" onkeyup="this.value=this.value.replace(/\s/g,‘‘)" id="introduce" placeholder=""></textarea> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">图片</label> <div class="col-sm-8"> <input type="file" class="uploadImg" id="url"/> </div> </div> <!--尾部--> <div class="modal-footer"> <button id="submit" type="submit" class="btn btn-primary">保存</button> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> </div> </form>
jQuery.validator.addMethod("isNotEmpty", function (value, element) {
value = value.replace(/\s/g,"");
return this.optional(element) || value;
}, "不能为空");
//初始化 表单验证
$("#brandForm").validate({
rules: {
//name 这里取的是页面name属性值
name: {
required: true,
isNotEmpty: true
},
introduce: {
isNotEmpty: true
}
},
invalidHandler: function () {
return false;
},
submitHandler: function () {
var formData = new FormData($("#brandForm").get(0));
$(".uploadImg").each(function () {
if ($(this).get(0).files[0]) {
var oImg = new Image();
oImg.src = $(this).siblings("img").get(0).src;
var type = $(this).get(0).files[0].type;
if (oImg.complete) {
callBack(type);
} else {
oImg.onload = callBack(type);
}
function callBack(type) {
var data = compress(oImg);
formData.append("file", upload(data, type));
}
}
});
if(!formData.get("id") && !formData.get("file")){
toastr.error("图片不能为空");
return false;
}
$.ajax({
type: "post",
url: "/product/brand/merge",
async: false,
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (result) {
if (result.success) {
toastr.success(result.module);
$(‘#brandModal‘).modal(‘hide‘);
$("#brandListTab").bootstrapTable("refresh");
} else {
toastr.error(result.errorMessage);
}
},
error: function (e) {
toastr.error(e.errorMessage);
}
});
}
});
//打开增加模态框 $("#addBrand").click(function () { $("#id").val(""); $("#name").val(""); $("#desc").val(""); $(".deleteItem").hide().siblings("img").hide().attr(‘src‘, ""); //打开模态框 $("#brandModal").modal(‘show‘); }); //修改 function update(id) { var brand = $(‘#brandListTab‘).bootstrapTable(‘getRowByUniqueId‘, id); console.log(brand); $("#id").val(id); $("#name").val(brand.name); $("#desc").val(brand.desc); //显示图片 if (brand.url) { $(".deleteItem").siblings("img").show().attr(‘src‘, brand.url); } $("#brandModal").modal("show"); }
原文:https://www.cnblogs.com/abo666/p/11248593.html