1.话不多说,直接上代码吧
1.前端页面文件:
<script type="text/javascript" src="${ctx }/static/js/lib/jquery.min.js"></script>
<script type="text/javascript" src="${ctx }/static/js/lib/uploadPreview.js"></script>
<!--
大家注意到这个form的target的了么?这个target属性的值frameFile,是form之后的iframe的name值,
这样的写法是让当前的form表单在提交表单内容的时候转交给iframe中进行页面中表单处理,
并且不会产生当前页面跳转!
-->
<form method="post" enctype="multipart/form-data" action="${ctx }/user/uploadImage.do" target='frameFile'>
<input type="hidden" name="id" value="${user.id }"/>
<input type="hidden" name="page" value="${page}"/>
<input type="file" id="logoFile" name="logoFile" style="display:none"/>
<a href="javascript:void(0)" οnclick="$('#logoFile').click();">
<img id="logo" style="height:130px;width:100px;border:1px solid #FFFFFF;"
<c:if test="${empty user.logoUrl }">src="../static/images/usericon/usericon1.png"</c:if>
<c:if test="${not empty user.logoUrl }">src="${user.logoUrl }"</c:if>
title="更换头像"/></a>
</form>
<!--
这个iframe拿到post过来的表单数据后会开始在自身内部访问post过来的页面地址,在内部中它会刷新页面,
但是这已不重要了,因为当前的iframe已经被我display:none隐藏了!所以这样给用户看起来像是无刷新的
页面文件上传,其实只是做一个一个小小的技巧!
-->
<iframe id='frameFile' name='frameFile' style='display: none;'></iframe>
2.js文件部分
//个人头像的上传
$("#logoFile").uploadPreview({ Img: "logo", Width: "100px", Height: "130px",ImgType: ["gif", "jpeg", "jpg", "bmp", "png"],
Callback: function () {
$(".logoUrl form").submit();
}
});
3.后台部分文件
@RequestMapping({ "/uploadImage.do" })
public String uploadImage(User user,HttpServletRequest request,HttpServletResponse response) throws IOException{
Map<String,Object> resultMap=new HashMap<String,Object>();
String uploadDir=ConfigHelper.getString("img.server.basedir");
String userDir=ConfigHelper.getString("upload.image.user.path");
String path=uploadDir+userDir;
//得到上传请求request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
try {
MultipartFile imageFile = multipartRequest.getFile("logoFile");
//获取文件名称
String fileName = imageFile.getOriginalFilename();
if(fileName!=null && fileName!=""){
// 获取文件后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 判断上传的文件格式是否正确
if ((".gif.jpg.jpeg.bmp.png".indexOf(suffix.toLowerCase()) == -1)) {
ajaxError(response, resultMap, MsgKeys.MSG_FILE_TYPE_INVALID, LanguageCodes.EN);
return null;
}
// 如果文件小于1M,则上传文件,否则提示用户不能超过1M
if (imageFile.getSize() > 1 * 1024 * 1024) {
ajaxError(response, resultMap, MsgKeys.MSG_FILE_SIZE_INVALID, LanguageCodes.EN);
return null;
}
File filePath = new File(path);
// 判读存储文件路是否存在,不存在则创建
if (!filePath.exists()) {
filePath.mkdirs();
}
String newFileName = UUID.randomUUID().toString() + suffix;
// 文件开始上传到服务器上
imageFile.transferTo(new File(filePath.getAbsolutePath() + "/" + newFileName));
user.setRealLogoUrl(userDir+"/" + newFileName);
userService.dynamicUpdate(user);
ajaxError(response, resultMap);
}
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return ErrorPages._500;
}
return null;
}