方式一:
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, "上传失败"); } }); } }
方式二(插件):
jQuery.form.js 参考:https://www.cnblogs.com/qlqwjy/p/7831927.html