关于图片上传

超、凢脫俗 2022-06-05 05:36 291阅读 0赞

添加图片jsp

  1. <form action="${path }/teacher/upHeadImg" method="post" enctype="multipart/form-data">
  2. <input type="file" name="phImage" value="phImage"/>
  3. <input type="submit">
  4. </form>

然后是controller

  1. //添加临床视频
  2. @RequestMapping(value="/addClinicVideo",method={RequestMethod.POST})
  3. public String addClinicVideo(Clinicvideo clinicvideo,HttpServletRequest request
  4. ,@RequestParam("phImage") MultipartFile file){
  5. //1.判断上传的头像是否为空
  6. if(!file.isEmpty()){
  7. //头像上传
  8. //2、指定上传目录
  9. String str=request.getSession().getServletContext().getRealPath("\\upload");
  10. System.out.println(str);
  11. //3、如果路径不存在,创建此路径
  12. File path=new File(str);
  13. System.out.println("path="+path);
  14. if(!path.exists()){
  15. path.mkdirs();
  16. }
  17. //4、获取名字
  18. String name=file.getOriginalFilename();
  19. //5、防止名字重复
  20. name=UUID.randomUUID()+name;
  21. //6、拼接路径 路径加名字 文件
  22. File desPath= new File(path, name);
  23. //7、文件上传
  24. try {
  25. //要上传的路径 , 文件-------字节数组
  26. FileUtils.writeByteArrayToFile(desPath, file.getBytes());
  27. } catch (IOException e) {
  28. // TODO Auto-generated catch block
  29. e.printStackTrace();
  30. }
  31. //8、把改路径设置到user里面数据库里D://xxxx//upload//user/xx.jpg
  32. clinicvideo.setImage(name);
  33. System.out.println(clinicvideo.getImage()+"数据库中路径");
  34. }
  35. clinicVideoService.add(clinicvideo);
  36. return "redirect:/clinicVideo/findClinicVideo";
  37. }

从代码中可以看出图片上传的路径为 项目webApp下的upload文件夹下,所以我需要再springmvc-action.xml中加入upload的资源路径映射

  1. <mvc:resources location="/upload/" mapping="/upload/**"/>

然后显示的图片

  1. <!--如果没有图片给定个默认图片-->
  2. <c:if test="${clinicVideo.image == null || clinicVideo.image ==''}">
  3. <img src="${pageContext.request.contextPath }/img/avatar_lg.png" width="100px" height="100px"> </c:if>
  4. <!--显示图片-->
  5. <c:if test="${clinicVideo.image != null && clinicVideo.image !=''}">
  6. <img class="img-thumbnail" src="${pageContext.request.contextPath}/upload/${clinicVideo.image}" width="100px" height="100px">
  7. </c:if>

注意上传包:

  1. < dependency >
  2. < groupId > commons-fileupload </ groupId >
  3. < artifactId > commons-fileupload </ artifactId >
  4. < version > 1.3.1 </ version >
  5. </ dependency >

springmvc-action.xml中配置

  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  2. <!-- 文件上传的大小 -->
  3. <property name="maxUploadSize" value="10200253"></property>
  4. </bean>

发表评论

表情:
评论列表 (有 0 条评论,291人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android关于图片如何压缩

    开发中遇到需要上传图片的场景还是很常见的,这就涉及到图片的压缩处理。如果不进行压缩,势必造成消耗大量的流量,下载图片的速度慢等。 关于android如何压缩,网上的资料也

    相关 图片

    开发工具与关键技术:Visual Studio 作者:肖广斌 撰写时间:2019年5月12日 在做项目时,我们在完善一些个人信息、或者一些页面时,我们需要用到图片,