点击头像实现头像上传预览
前端代码
<style>
#addImgDiv{
width: 64px;
height: 64px;
float: left;
border-radius: 50%;
border: 3px solid #eee;
overflow: hidden;
background-image: url("/img/userImgs/defUser.jpg");
background-size: cover;
text-align: center;
}
</style>
<body>
<form action="/addPic" method="post" role="form" enctype="multipart/form-data">
<div class="input-field col s12" style="padding-left: 38%">
<div id="addImgDiv">
<input id="addImg" name="img" type="file" style="opacity: 0;width: 64px;height: 64px" accept=".jpg,.png,.gif"/>
</div>
</div>
</form>
<script>
$("#addImg").change(function () {
var img=$("#addImg")[0].files
var file=img[0];
console.log(img);
console.log(file)
var URL = window.URL || window.webkitURL;
// 通过 file 生成目标 url
var imgURL = URL.createObjectURL(file);
// 用这个 URL 产生一个 <img> 将其显示出来
$("#addImgDiv").css("background-image","url("+imgURL+")");
console.log(imgURL)
});
</script>
后台代码:
@RequestMapping(value = "/addPic")
public String addUser(HttpServletRequest request, @RequestPart("img") MultipartFile picture) throws IOException {
String filename = picture.getOriginalFilename();
String realPath = request.getServletContext().getRealPath("/img");
String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0,9);
//默认选择defUser.jpg
String imgPath=realPath+"/userImgs/defUser.jpg";
//没有选择默认头像。。。。
if (!("".equals(filename)||filename==null)){
imgPath=realPath+"/userImgs/"+uuid+filename;
}
picture.transferTo(new File(imgPath));
}