-
方式一:
jsp代码: <div class="inputItem" style="justify-content: flex-start;padding-left: 44px;"> <div class="inputName">人脸采集</div> <img id="userImage1" onclick="uploadFace1();" src="" alt="默认图片" style="height: 60px;width: 60px;"> </div> <form id="addMultiDeviceFm" hidden class="form-horizontal"> <div class="form-group"> <label for="file" class="col-sm-4 control-label">上传文件:</label> <div class="col-sm-5"> <div class="input-group"> <input type="file" id="file" name="file" accept="image/bmp,image/png,image/jpg" onchange="MutilInput(this)"> </div> </div> </div> </form> js代码: function uploadFace1() { $("#file").click(); } function MutilInput(a) { var fileSize = ""; var fileMaxSize = 1024;//1M if (a.files.length == 0) { return; } else { fileSize =a.files[0].size; var size = fileSize / 1024; if (size > fileMaxSize) { alertMsg(2, "文件大小不能大于1兆"); a.value = ""; return false; } var form = new FormData(document.getElementById("addMultiDeviceFm")); $.ajax({ type: "post", url: "",//文件上传的路径地址 data: form, processData: false, contentType: false, beforeSend: function () { showLoader() }, success: function (data) { hideLoader(); var json = data; if (json.flag) { alertMsg(1, "图片上传成功"); //$("#userImage").css("height", "167px");//记得改id //$(".upload-pic-ope").css("display", "flex"); $('#userImage').attr("src", json.url); picName = json.fileName; picUrl = json.url; } else { alertMsg(3, json.msg); } }, error: function (e) { hideLoader(); alertMsg(3, "上传失败"); } }); } }
当点击默认图片时,调用uploadFace1函数来触发form表单中的文件框,文件框发生改变时调用onchange事件MutilInput,当图片的格式和大小满足要求时调用接口上传图片
-
方式二(插件):
jQuery.form.js 参考:https://www.cnblogs.com/qlqwjy/p/7831927.html
本文地址:http://www.45fan.com/a/question/99673.html