使用三種插件css
uploadImg.min.cssajax
uploadImg.min.jsbootstrap
CompressImgUpload.jsapp
class = "uploadImg"async
<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"); }