springMVC学习(10)-上传图片
需求:在修改商品页面,添加上传商品图片功能。
SpringMVC中对多部件类型解析:
1)springmvc中配置:
1 <!-- 文件上传 --> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <!-- 设置上传文件的最大尺寸为5MB --> 4 <property name="maxUploadSize"> 5 <value>5242880</value> 6 </property> 7 </bean>
View Code
需要加入的jar包:(上边的解析器就是使用下面的jar包进行图片上传)
commons-fileupload-1.2.2.jar;
commons-io-2.4.jar
2)editItems.jsp中form的enctype要设置为“multipart/form-data”;
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>修改商品信息</title> 10 11 </head> 12 <body> 13 14 <!-- 显示错误信息 --> 15 <c:if test="${allErrors!=null}"> 16 错误信息:<br/> 17 <c:forEach items="${allErrors}" var="error"> 18 ${error.defaultMessage}<br/> 19 </c:forEach> 20 </c:if> 21 22 <form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data"> 23 <input type="hidden" name="id" value="${items.id }"/> 24 修改商品信息: 25 <table width="100%" border=1> 26 <tr> 27 <td>商品名称</td> 28 <td><input type="text" name="name" value="${items.name }"/></td> 29 </tr> 30 <tr> 31 <td>商品价格</td> 32 <td><input type="text" name="price" value="${items.price }"/></td> 33 </tr> 34 <tr> 35 <td>商品生产日期</td> 36 <td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td> 37 </tr> 38 <tr> 39 <td>商品图片</td> 40 <td> 41 <c:if test="${items.pic !=null}"> 42 <img src="/pic/${items.pic}" width=100 height=100/> 43 <br/> 44 </c:if> 45 <input type="file" name="items_pic"/> 46 </td> 47 </tr> 48 <tr> 49 <td>商品简介</td> 50 <td> 51 <textarea rows="3" cols="30" name="detail">${items.detail }</textarea> 52 </td> 53 </tr> 54 <tr> 55 <td colspan="2" align="center"><input type="submit" value="提交"/> 56 </td> 57 </tr> 58 </table> 59 </form> 60 </body> 61 </html>
View Code
3)controller中代码:
这里是设置tomcat的虚拟目录的:在tomcat中图片访问路径是/pic,真实的物理地址是D:\upload\images;
对应tomcat conf/server.xml中的配置是:
<Context docBase="D:\upload\images" path="/pic" reloadable="false"/>
Contorller处理上传文件,并将文件名设置到数据库代码:
1 //商品信息修改提交 2 @RequestMapping("/editItemsSubmit") 3 public String editItemsSubmit(Model model, 4 HttpServletRequest request, 5 Integer id, 6 @Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult, 7 MultipartFile items_pic) 8 throws Exception { 9 if(bindingResult.hasErrors()){ 10 List<ObjectError> allErrors = bindingResult.getAllErrors(); 11 for(ObjectError objectError : allErrors){ 12 System.out.println(objectError.getDefaultMessage()); 13 } 14 15 // 将错误信息传到页面 16 model.addAttribute("allErrors", allErrors); 17 18 //可以直接使用model将提交pojo回显到页面 19 model.addAttribute("items", itemsCustom); 20 21 return "items/editItems"; 22 } 23 24 String originalFilename = items_pic.getOriginalFilename(); 25 26 if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){ 27 String pic_path = "D:\\upload\\images\\"; 28 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); 29 30 //新图片 31 File newFile = new File(pic_path + newFileName); 32 33 items_pic.transferTo(newFile); 34 35 itemsCustom.setPic(newFileName); 36 } 37 38 itemsService.updateItems(id, itemsCustom); 39 return "success"; 40 }
View Code
上传图片成功:
4)修改代码将图片上传到项目路径中WebRoot/resources/images:
新建存放图片的文件夹:
我这边先是在web-inf下面放的图片;工程是发布在org.eclipse.wst.server.core\tmp0\wtpwebapps下面;做了好几次实验,页面上就是不能展示修改后的图片;
后来把工程发布在tomcat的安装目录、资源文件放在项目根路径/WebRoot下面resources的;
//商品信息修改提交//MultipartFile 接收商品图片@RequestMapping("/editItemsSubmit")public String editItemsSubmit(Model model,HttpServletRequest request,Integer id, @Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,BindingResult bindingResult,MultipartFile items_pic)throws Exception {if(bindingResult.hasErrors()){List<ObjectError> allErrors = bindingResult.getAllErrors();for(ObjectError objectError : allErrors){System.out.println(objectError.getDefaultMessage());}// 将错误信息传到页面model.addAttribute("allErrors", allErrors);//可以直接使用model将提交pojo回显到页面model.addAttribute("items", itemsCustom);return "items/editItems";}//文件原始名称String originalFilename = items_pic.getOriginalFilename();if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){/** 1 这里上传到tomcat部署环境下面的WebRoot/resources/images/下面了* 因为真正项目部署后运行环境,这里就想传到这个下面;*/String basePath = request.getServletContext().getRealPath("resources/images/");System.out.println("文件保存路径--------------------------->>" + basePath);//String basePath = request.getServletContext().getRealPath("WEB-INF/resources/images/");//E:\jdbcWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\springMVC\WEB-INF\resources\images\/* 2 1和2的效果是一摸一样;System.out.println("类名:-------------------------------" + this.getClass().getName());//ItemsControllerString basePath = this.getClass().getClassLoader().getResource("../../WEB-INF/resources/images/").getPath();System.out.println("文件保存路径--------------------------" + basePath);//E:\jdbcWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\springMVC\WEB-INF\resources\images\*///新的图片名称String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));//新图片File newFile = new File(basePath + newFileName);//将内存中的数据写入磁盘 items_pic.transferTo(newFile);itemsCustom.setPic(newFileName);}itemsService.updateItems(id, itemsCustom);return "success";}
springmvc.xml中配置了静态资源访问:
看到说这个的前提是配置了注解驱动:mvc:annotation-driven
1 <!-- 对静态资源文件的访问 2 mapping:映射 3 两个*,它表示映射resources/下所有的URL,包括子路径(即接多个/) 4 location:本地资源路径,默认是webapp根目录下的路径。 5 WEB-INF是Java的WEB应用的安全目录。所谓安全就是客户端无法访问,只有服务端可以访问的目录。 6 --> 7 <mvc:resources mapping="/resources/**" location="/resources/" />
editItems.jsp:
<tr><td>商品图片</td><td><c:if test="${items.pic !=null}"><img src="${pageContext.request.contextPath }/resources/images/${items.pic}" width=100 height=100/><br/></c:if><input type="file" name="items_pic"/> </td> </tr>
页面上再上传图片,能够看到:
图片保存在tomcat/webapps/springMVC/resources/images下面:
转载于:https://www.cnblogs.com/tenWood/p/6337070.html
springMVC学习(10)-上传图片相关推荐
- SpringMVC学习10之AJAX初体验和了解
Ajax了解 AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML). AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网 ...
- SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传
SpringMVC:学习笔记(10)--整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...
- springmvc学习笔记(10)-springmvc注解开发之商品改动功能
springmvc学习笔记(10)-springmvc注解开发之商品改动功能 springmvc学习笔记(10)-springmvc注解开发之商品改动功能 标签: springmvc springmv ...
- springmvc学习笔记(17)-上传图片
2019独角兽企业重金招聘Python工程师标准>>> springmvc学习笔记(17)-上传图片 标签: springmvc [TOC] 本文展示如何在springmvc中上传图 ...
- springmvc学习笔记--ueditor和springmvc的集成
springmvc学习笔记--ueditor和springmvc的集成 前言: 在web开发中, 富文本的编辑器真心很重要. 有电商店铺的打理, 新闻稿/博客文章/论坛帖子的编辑等等, 这种所见即所的 ...
- SpringMVC学习
SpringMVC介绍 SpringMVC是什么? SpringMVC和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来: SpringMVC ...
- SpringMVC学习笔记
文章目录 SpringMVC学习笔记 Spring MVC 什么是 MVC 设计模式? Spring MVC 的核心组件 Spring MVC 的工作流程 如何使用? Spring MVC 注解 Sp ...
- SpringMVC学习--文件上传
简介 文件上传是web开发中常见的需求之一,springMVC将文件上传进行了集成,可以方便快捷的进行开发. springmvc中对多部件类型解析 在 页面form中提交enctype="m ...
- SpringMVC学习笔记整理
SpringMVC学习笔记 以下是我整理的SpringMVC学习笔记: 导入jar包 一:springmvc工作流程. ①. servlet容器初始化一个request请求 ②. Di ...
- (转)SpringMVC学习(五)——SpringMVC的参数绑定
http://blog.csdn.net/yerenyuan_pku/article/details/72511611 SpringMVC中的参数绑定还是蛮重要的,所以单独开一篇文章来讲解.本文所有案 ...
最新文章
- 刷题2个月,终于进了梦寐以求的大厂,数据结构和算法太TM重要了!
- MySQL列的别名 insert into select from
- 好书 《古代的中医》 《麦肯锡卓越工作方法》
- BootStrap字体图标不显示、下拉菜单不显示
- BZOJ1801: [Ahoi2009]chess 中国象棋
- php识别地址,实现地址自动识别实例(PHP)
- 这是我看过最精彩的回答
- 一个简单示例 利用jawin完成调用window中dll的调用
- Python得到n个从start到end的不重复随机数(set实现)
- Python根据mask在原图上进行标记
- 解决python的OverflowError: int too large to convert to float
- Chrome OS Factory开发测试流程
- 为什么html中图片显示不出来,网页图片不能显示 网页图片显示不出来的解决办法...
- 【重要】国庆节快乐!有三AI所有课程限时7天优惠
- 从“棱镜门”事件看数据安全如何保护
- 面对众多云数据库,应该使用哪个云数据库好?
- 在国内用Windows给BT做种,真是一山绕过一山缠(附解决方案)
- 学习笔记 | NIPS 2021 regularization cocktail 调优的 MLPs 在表格数据上优于 GBDTs | Regularization is All Your Need
- EasyExcel设置行中单个单元格的样式
- xff_referer知识
热门文章
- 打仗最害怕的是什么?后方出事
- 根据眼睛焦点分级绘制3D效果的设想
- linux下用top命令查看,cpu利用率超过100%时怎么回事
- 管理感悟:正确认识自己的工作
- 集美大学计算机工程学院 曾勇进,电子政务评估方法AHP 的研究及实现.pdf
- Dxg——立创EDA [LCEDA] 开发笔记整理分类合集【所有的相关记录,都整理在此】
- mysql扩展函数创建临时表_MySQL函数中创建临时表
- stm32如何设置蜂鸣器温度报警_有人喊冷?有人喊热?列车空调温度到底如何设置...
- 用python开发的运维管理系统_Python运维三十六式:用Python写一个简单的监控系统...
- mysql innodb 分区表_InnoDB的分区表