使用springmvc+ajax+formdata上图片(上传完成,立即回显),图片存放在服务器中,在数据中存入图片在服务器中的url,以获取图片。
html:
<div class="userPhoto" style="width: 800px">
<form id="formUp" action="" enctype="multipart/form-data">
<input type="hidden" id="userId" value="${SessionUser.id }" name="userId" />
<table style="width: 800px">
<tr>
<td width="150px"><img id="showPhoto" alt="暂无图片" src="${SessionUser.photo }"></td>
<td align="left"><input type="button" id="button_submit" value="选择图片" /></td>
<td style="display: none;"><input type="file" id="photoUp" name="image" value="上传图片" /></td>
</tr>
</table>
</form>
</div>
jquery:
$("#button_submit").click(function(){
$("#photoUp").click();
});
$("#photoUp").change(function(){
var formData = new FormData($("#formUp")[0]);
$.ajax({
url:"userPhotoUplaod.do",
type:"post",
data : formData,
async : false,
cache : false, //cache设置为false,上传文件不需要缓存。
contentType : false, //contentType设置为false。因为是由<form>表单构造的FormData对象,且已经声 //明了属性enctype="multipart/form-data",所以这里设置为false。
processData : false, //processData设置为false。因为data值是FormData对象,不需要对数据做处理。
success : function(data) {
if(data.upload == "success"){
$("#showPhoto").attr("src",data.photoUrl);
$("#showPhoto").attr("width","150");
$("#showPhoto").attr("height","150");
/* $("#showPhoto").attr("src","showImages.do?name=image&"+new Date().toTimeString());
$("#showPhoto").attr("width","150");
$("#showPhoto").attr("height","150"); */
}
},
});
});
control层:
@RequestMapping("userPhotoUplaod")
@ResponseBody
public Map<String,Object> upLoad(HttpServletRequest request,HttpServletResponse response,Integer userId) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
// 从请求中获取到文件信息需要将请求转换为MultipartHttpServletRequest类型
MultipartHttpServletRequest multipartRequest = request instanceof MultipartHttpServletRequest ? (MultipartHttpServletRequest) request : null;
MultipartFile file = multipartRequest.getFile("image");
String fileType = file.getContentType();
if(file.getSize() != 0 && ("image/bmp".equals(fileType) ||"image/jpeg".equals(fileType) || "image/png".equals(fileType) ) ){ //限制只能上传jpeg,bmp,jpg,png格式的图片
String fileName = file.getOriginalFilename();
int formIndex = fileName.lastIndexOf(".");
String suffix = fileName.substring(formIndex, fileName.length());
String path = request.getServletContext().getRealPath(File.separator);
File savePath = new File(path+File.separator+"photo");
if(!savePath.exists()){
savePath.mkdir();
}
InputStream input = file.getInputStream();
Users user = userService.getUserById(Users.class,userId);
if(null != user){
user.setPhoto(request.getContextPath()+"/photo"+"/"+user.getLoginName()+suffix);
@SuppressWarnings("unused")
boolean flag = userService.updateUser(user);
request.getSession().removeAttribute(Contance.Session.SESSION_USER);
request.getSession().setAttribute(Contance.Session.SESSION_USER, user);
OutputStream output = new FileOutputStream(savePath+File.separator+user.getLoginName()+suffix);
int b = 0;
while((b = input.read()) != -1){
output.write(b);
}
output.close();
input.close();
map.put("upload", "success");
map.put("photoUrl", user.getPhoto());
}
}else{
map.put("upload", "failed");
}
return map;
}