1. Add a virtual directory, find the Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"></Host> tag in tomcat's server.xml, and add <Context docBase to this tag ="D:\TestM\photo" path="/photo" reloadable="false"/> (set D:\TestM\photo as a virtual directory here, you can set it according to your own needs)
2. Upload the html of the image:
<div class="userPhoto" style="width: 800px">
<form id="formUp" action="" enctype="multipart/form-data">
<input type="hidden" id="userId" value="${userInfo.id }" name="userId" />
<table style="width: 800px">
<tr>
<td width="150px"><img id="showPhoto" alt="暂无图片" src="/photo/${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>
3. js for uploading pictures:
$("#showPhoto").attr("width","150");
$("#showPhoto").attr("height","150");
$("#button_submit").click(function(){
$("#photoUp").click();
});
$("#photoUp").change(function(){
var formData = new FormData($("#formUp")[0]);
var aaa = "aaa";
$.ajax({
url:"userPhotoUplaod.do",
type:"post",
data : formData,
async : false,
cache : false,
contentType : false,
processData : false,
success : function(data) {
if(data.upload == "success"){
$("#showPhoto").attr("src","/photo/"+data.photoUrl);
/* $("#showPhoto").attr("src","showImages.do?name=image&"+new Date().toTimeString());
$("#showPhoto").attr("width","150");
$("#showPhoto").attr("height","150"); */
}
},
});
});
4、上传图片的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 imgRealPath = "D:\\TestM\\photo"; //此处对应的自己配置的虚拟目录路径
File savePath = new File(imgRealPath);
if(!savePath.exists()){
savePath.mkdir();
}
InputStream input = file.getInputStream();
Users user = userService.getUserById(Users.class, userId);
if(null != user){
user.setPhoto(user.getLoginName()+suffix); //在数据库中保存图片名字(图片url)
userService.updateUser(user);
request.getSession().removeAttribute(Contance.Session.SESSION_USER);
request.getSession().setAttribute(Contance.Session.SESSION_USER,user);
OutputStream output = new FileOutputStream(imgRealPath+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;
}
5、显示图片:
在第二步,和第三步中已标注出,显示图片应该注意的路径。因为配置的虚拟路径的path=“/photo”,所以在读取图片时,只需要读 /photo/存在数据库中的图片url 即可。
注意: 要在 spring-mvc.xml中配置
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
否则不能支持文件上传