在做头像上传的过程中通常是将图片保存到数据库中,这里简单介绍一中将图片保存到数据库的方法:
jsp代码:
<div>
<input class="avatar-input" id="avatarInput" name="avatar_file" type="file" />
<button class="btn btn-primary btn-block avatar-save" type="button" id="btn">完成</button>
</div>
//显示头像
<div>
<img id="image" src="${pageContext.request.contextPath}/Personal.do?method=Pictureshow" />
</div>
js代码:
$("#avatarInput").wrap("<form id='myupload' action='${pageContext.request.contextPath}/Personal.do?method=Pictureupload' enctype='multipart/form-data' method='post' ></form>")
var formdata;
$("#avatarInput").change(function(){
formdata=new FormData($("#myupload")[0]);
})
$("#btn").click(function(){
$.ajax({
type: 'post',
url: '${pageContext.request.contextPath}/Personal.do?method=Pictureuplo',
data: formdata,
async:false,
cache:false,
contentType:false,
processData:false,
success: function(data) {
alert(data);
}
});
});
注:为了方便获取返回值,我这里选择用ajax传值,根据需求而定,也可以直接用form表单传值。
Controller(头像插入):
@RequestMapping(params = "method=Pictureupload",headers="content-type=multipart/*" ,method=RequestMethod.POST)
public @ResponseBody int Pictureupload(@RequestParam("avatar_file")MultipartFile file,HttpServletRequest request)throws Exception{
Map map=new HashMap<>();
int YGID001 = (int)request.getSession().getAttribute("ygid001");
String name = file.getOriginalFilename();
long filesize = file.getSize();
//System.err.println(filesize);
if(filesize>200000){//判断图片大小
return -1;
}
//System.out.println(file.getBytes());
map.put("in", file.getBytes());
map.put("YGID001", YGID001);
return pcs.Pictureupload(map);//pcs为service中方法。
}
Controller(头像显示):
@RequestMapping(params = "method=Pictureshows")
public ResponseEntity<byte[]> Pictureshow(HttpServletRequest request)throws Exception{
int YGID001 = (int)request.getSession().getAttribute("ygid001");
List<PictureShow> list=pcs.Pictureshows(YGID001);//根据员工号查找头像
byte[] bytes=list.get(0).getPortrait();
HttpHeaders headers = new HttpHeaders();
try {
headers.setContentType(MediaType.IMAGE_PNG);
headers.setContentDispositionFormData("attachment", new String("头像".getBytes("GBK"),"ISO8859-1"));
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(bytes,headers,HttpStatus.OK);
}
sql:
<!-- 头像插入 -->
insert into yg01 (SKYG018) values(#{in}) where YGID001=#{YGID001}
<!-- 头像显示 -->
select portrait from yg where YGID001=#{YGID001}
注:数据库字段类型设置为以下中的一种:TinyBlob 最大255 、 Blob 最大65K、 MediumBlob 最大16M、LongBlob 最大4G。