关于图片上传
添加图片jsp
<form action="${path }/teacher/upHeadImg" method="post" enctype="multipart/form-data">
<input type="file" name="phImage" value="phImage"/>
<input type="submit">
</form>
然后是controller
//添加临床视频
@RequestMapping(value="/addClinicVideo",method={RequestMethod.POST})
public String addClinicVideo(Clinicvideo clinicvideo,HttpServletRequest request
,@RequestParam("phImage") MultipartFile file){
//1.判断上传的头像是否为空
if(!file.isEmpty()){
//头像上传
//2、指定上传目录
String str=request.getSession().getServletContext().getRealPath("\\upload");
System.out.println(str);
//3、如果路径不存在,创建此路径
File path=new File(str);
System.out.println("path="+path);
if(!path.exists()){
path.mkdirs();
}
//4、获取名字
String name=file.getOriginalFilename();
//5、防止名字重复
name=UUID.randomUUID()+name;
//6、拼接路径 路径加名字 文件
File desPath= new File(path, name);
//7、文件上传
try {
//要上传的路径 , 文件-------字节数组
FileUtils.writeByteArrayToFile(desPath, file.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//8、把改路径设置到user里面数据库里D://xxxx//upload//user/xx.jpg
clinicvideo.setImage(name);
System.out.println(clinicvideo.getImage()+"数据库中路径");
}
clinicVideoService.add(clinicvideo);
return "redirect:/clinicVideo/findClinicVideo";
}
从代码中可以看出图片上传的路径为 项目webApp下的upload文件夹下,所以我需要再springmvc-action.xml中加入upload的资源路径映射
<mvc:resources location="/upload/" mapping="/upload/**"/>
然后显示的图片
<!--如果没有图片给定个默认图片-->
<c:if test="${clinicVideo.image == null || clinicVideo.image ==''}">
<img src="${pageContext.request.contextPath }/img/avatar_lg.png" width="100px" height="100px"> </c:if>
<!--显示图片-->
<c:if test="${clinicVideo.image != null && clinicVideo.image !=''}">
<img class="img-thumbnail" src="${pageContext.request.contextPath}/upload/${clinicVideo.image}" width="100px" height="100px">
</c:if>
注意上传包:
< dependency >
< groupId > commons-fileupload </ groupId >
< artifactId > commons-fileupload </ artifactId >
< version > 1.3.1 </ version >
</ dependency >
springmvc-action.xml中配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 文件上传的大小 -->
<property name="maxUploadSize" value="10200253"></property>
</bean>
还没有评论,来说两句吧...