一、后台
@RequestMapping("/tea/modifyTeaAvatar")
public @ResponseBody JsonResult modifyTeaAvatar(HttpServletRequest request,HttpServletResponse response,
int x,int y,int w,int h){
try{
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
MultipartFile multFile = multiRequest.getFile("imgFile");
ImageInputStream iis = null;
if (multFile == null || multFile.isEmpty())
return new JsonResult(false,"文件为空");
// 扩展名格式:
String extName = "";
String message = "";
String newName = "";
boolean flag = true;
//取得上传的文件名
String fileName = multFile.getOriginalFilename();
if(fileName != null && !"".equals(fileName.trim())){
long size = multFile.getSize();
if(size > (1024*1024)){
message = "只允许上传1M之内的图片";
flag = false;
return new JsonResult(flag,message);
}
if (fileName.lastIndexOf(".") >= 0) {
extName = fileName.substring(fileName.lastIndexOf("."));
}
if(!checkSpecialFileType(extName.toLowerCase())){
message = "只允许上传jpg,jpeg,gif,png格式的图片";
flag = false;
return new JsonResult(flag,message);
}
String root=request.getSession().getServletContext().getRealPath("/");
String savePath = root+File.separator+Constants.USER_HEAD_PHOTO_PATH+File.separator;
File f1 = new File(savePath);
if (!f1.exists()) {
f1.mkdirs();
}
if(flag){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ssSSS");
Calendar calendar = Calendar.getInstance();
//以当前时间为文件名 格式如:2011-09-03-19-30-36047
newName = df.format(calendar.getTime());
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(new String(extName.substring(1).getBytes(),"utf-8"));
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(multFile.getInputStream());
reader.setInput(iis,true);
ImageReadParam param = reader.getDefaultReadParam();
Rectangle rect = new Rectangle(x, y, w, h);
param.setSourceRegion(rect);
BufferedImage bi = reader.read(0,param);
ImageIO.write(bi, extName.substring(1), new File(savePath + newName + extName));
FtpUtil client = new FtpUtil();
if(!client.connectByConstants()) return new JsonResponse(false,"上传失败"); //上传失败!
client.uploadByInputStream(multFile.getInputStream(), Constants.FTP_IMAGE_PATH, newName+extName);
User user = SystemUtil.getCurrentUser(request);
user.setUserHeadPhoto(newName + extName);
int i = userService.update(user.getUserId(), new String[]{"userId","userHeadPhoto"}, new Object[]{user.getUserId(),newName + extName});
if(i<=0) throw new Exception("头像更新失败");
}
}
return new JsonResult(true,newName+extName);
}catch(Exception e){
return new JsonResult(false,"上传失败");
}
}
二、前台
需要添加Jcrop插件
<script src="${ctx }/js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="${ctx }/css/jquery.Jcrop.min.css" type="text/css" />
<div class="mechanism_main1" style="display:none;">
<div class="modify_l">
<div class="modify_l_z">当前头像</div>
<c:if test="${empty user.userHeadPhoto}"><img id="headPhoto" src="images/user_pic.jpg" width="180" height="190" /></c:if>
<c:if test="${!empty user.userHeadPhoto}"><img id="headPhoto" src="${fileUrl}/${user.userHeadPhoto}" width="180" height="190" /></c:if>
</div>
<div class="modify_l">
<div class="modify_l_z">更改头像(成功后请手动刷新)</div>
<p>请选择新的照片文件,文件需小于5MB</p>
<ul>
<form id="myForm" name="myForm" action="${ctx}/tea/modifyTeaAvatar.shtml" method="post" enctype="multipart/form-data">
<input style="width:240px; border:1px solid #ccc; height:25px;" type="file" name="imgFile" id="fcupload" onchange="readURL(this);"/>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<li><input type="submit" value="上传" id="upload" class="cinput"/></li>
</form>
<img alt="头像" src="" id="displayImg" style="width: 240px;height: 240px;display:none"/>
</ul>
</div>
</div>
js 解决了提交后图片隐藏问题;同时解决切换上传图片需要重新打开页面问题。
$(function() {
$("#myForm").submit(function() {
if(checkForm()){
$(this).ajaxSubmit({
url: "${ctx}/tea/modifyTeaAvatar.shtml",
data: $("#myForm").serialize(),
type: "POST",
dataType:"json",
success: function(json) {
if(!json.flag){
window.alert(json.result);
}else{
window.alert("成功");
$("#headPhoto").attr("src","${fileUrl}/"+json.result);
$("#headPhotoleft").attr("src","${fileUrl}/"+json.result);
$("#displayImg").remove();
$("#myForm").after(' <img alt="头像" src="" id="displayImg" style="width: 240px;height: 240px;display:none"/>');
$(".jcrop-holder").remove();
}
}
});
}else{
window.alert("请检查表单必填项,是否填写");
}
return false;
});
});
function readURL(input) {
$("#displayImg").remove();
$(".jcrop-holder").remove();
$("#myForm").after(' <img alt="头像" src="" id="displayImg" style="width: 240px;height: 240px;display:none"/>');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e){
$("#displayImg").attr("src", e.target.result);
var api = $("#displayImg").Jcrop({
setSelect:[0,0,240,240],
aspectRatio: 1,
onSelect: updateCoords
});
}
reader.readAsDataURL(input.files[0]);
}
}
function updateCoords(c){
$("#x").val(c.x);
$("#y").val(c.y);
$("#w").val(c.w);
$("#h").val(c.h);
};