一、功能实现
<div class="col-lg-4 col-sx-4 col-md-4" style="margin-top:20px;">
<h4 class="Hongse">用户照片:</h4>
<div class="img-box text-center" style="width:220px;height:250px;border-style:double;margin:0px;">
<img src="" alt="" width="150" height="180" id="IimgStudentPicture" style="margin-top:25px;" />
</div>
<div style="margin-top:10px">
<input type="file" style="margin-left:90px;margin-top:200px;margin:0px" name="activityimg" id="IStudentPicture" />
</div>
</div>
//选择照片
var imgReaderI = new FileReader();
regexImageFilter = /^(?:image\/bmp|image\/png|image\/jpeg|image\/jpg)$/i;
//文件读取 onload事件
imgReaderI.onload = function (evt) {
$("#IimgStudentPicture").attr("src", evt.target.result);
$("#modalimg").attr("src",evt.target.result);
};
$("#IStudentPicture").change(function () {
var IStudentPictureVal = $("#IStudentPicture").val().trim();
if(IStudentPictureVal == "" && IStudentPictureVal == null){
$("#IimgStudentPicture").attr("src", "");
}
var imgfFile = $("#IStudentPicture").prop('files')[0];
if (!regexImageFilter.test(imgfFile.type)) {
layer.alert('选择的不是一个有效的图片文件', { icon: 6 });
}else if (imgfFile.size >= 4 * 1024 * 1024) {
layer.alert("图片文件不能大于4MB");
$("#IStudentPicture").val("");
return false;
}else{
imgReaderI.readAsDataURL(imgfFile);
}
});
Form表单中form标签中请加上 : enctype=\"multipart/form-data\" (是关于文件传输的)
//Java Servlet中加上判断
if (!ServletFileUpload.isMultipartContent(req)) {
System.out.println("Error:表单必须包含enctype=\"multipart/form-data\"");
resp.getWriter().write("fail");
//jsonReturn.setMsg("Error:表单必须包含enctype=\"multipart/form-data\"");
} else{
}