springMVC学习(10)-上传图片
需求:在修改商品页面,添加上传商品图片功能。
SpringMVC中对多部件类型解析:
1)springmvc中配置:
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
需要加入的jar包:(上边的解析器就是使用下面的jar包进行图片上传)
commons-fileupload-1.2.2.jar;
commons-io-2.4.jar
2)editItems.jsp中form的enctype要设置为“multipart/form-data”;
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title> </head>
<body> <!-- 显示错误信息 -->
<c:if test="${allErrors!=null}">
错误信息:<br/>
<c:forEach items="${allErrors}" var="error">
${error.defaultMessage}<br/>
</c:forEach>
</c:if> <form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${items.id }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${items.name }"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${items.price }"/></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
</tr>
<tr>
<td>商品图片</td>
<td>
<c:if test="${items.pic !=null}">
<img src="/pic/${items.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="items_pic"/>
</td>
</tr>
<tr>
<td>商品简介</td>
<td>
<textarea rows="3" cols="30" name="detail">${items.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</body>
</html>
3)controller中代码:
这里是设置tomcat的虚拟目录的:在tomcat中图片访问路径是/pic,真实的物理地址是D:\upload\images;

对应tomcat conf/server.xml中的配置是:
<Context docBase="D:\upload\images" path="/pic" reloadable="false"/>
Contorller处理上传文件,并将文件名设置到数据库代码:
//商品信息修改提交
@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){
String pic_path = "D:\\upload\\images\\";
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); //新图片
File newFile = new File(pic_path + newFileName); items_pic.transferTo(newFile); itemsCustom.setPic(newFileName);
} itemsService.updateItems(id, itemsCustom);
return "success";
}
上传图片成功:

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());
//ItemsController
String 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
<!-- 对静态资源文件的访问
mapping:映射
两个*,它表示映射resources/下所有的URL,包括子路径(即接多个/)
location:本地资源路径,默认是webapp根目录下的路径。
WEB-INF是Java的WEB应用的安全目录。所谓安全就是客户端无法访问,只有服务端可以访问的目录。
-->
<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下面:

springMVC学习(10)-上传图片的更多相关文章
- 【SpringMVC学习10】SpringMVC对RESTfull的支持
RESTful架构,就是目前流行的一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以正得到越来越多网站的采用.RESTful架构对url进行规范,写RESTful格式的url是什么样子 ...
- SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传
SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...
- springmvc学习笔记(10)-springmvc注解开发之商品改动功能
springmvc学习笔记(10)-springmvc注解开发之商品改动功能 标签: springmvc springmvc学习笔记10-springmvc注解开发之商品改动功能 需求 开发mappe ...
- SpringMVC学习系列-后记 结合SpringMVC和Hibernate-validator,根据后台验证规则自动生成前台的js验证代码
在SpringMVC学习系列(6) 之 数据验证中我们已经学习了如何结合Hibernate-validator进行后台的数据合法性验证,但是通常来说后台验证只是第二道保险,为了更好的用户体验会现在前端 ...
- springmvc学习笔记--REST API的异常处理
前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...
- springmvc学习笔记(简介及使用)
springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...
- springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解
@_@ 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) myba ...
- springMVC 学习笔记(一):springMVC 入门
springMVC 学习笔记(一):spring 入门 什么是 springMVC springMVC 是 spring 框架的一个模块,springMVC 和 spring 无需通过中间整合层进行整 ...
- (转)SpringMVC学习(五)——SpringMVC的参数绑定
http://blog.csdn.net/yerenyuan_pku/article/details/72511611 SpringMVC中的参数绑定还是蛮重要的,所以单独开一篇文章来讲解.本文所有案 ...
随机推荐
- strtus2 文件上传
struts2和spring mvc上传都是用 common-fileupload来实现 1.struts2上的方式需要在对应的Action,加上如下的属性以及get/set方法 private Fi ...
- 【数据库】MFC ODBC(四)
7.滚动记录 CRecordset提供了几个成员函数用来在记录集中滚动.当用这些函数滚动到一个新记录时,框架会自动地把新记录的内容拷贝到域数据成员中. void MoveNext( ); //前进一个 ...
- CODE大全大量Flash网站收藏
我的博客:CODE大全:www.codedq.net:业余草:www.xttblog.com:爱分享:www.ndislwf.com或ifxvn.com. http://www.wallop.com在 ...
- 1.1.3 A+B for Input-Output Practice (III)
A+B for Input-Output Practice (III) Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 ...
- XDocument 使用
摘要: 正文: 1.引入XDocument的命名空间 using System.Xml.Linq; 2. List<CourseItem> to XML doc //List<Cou ...
- Windows下C++删除清除map
清除单map(非嵌套map) #include<map> #include<string> #include<iostream> using namespace s ...
- 洛谷 1192:台阶问题(递推,DP)
题目描述 有 N 级的台阶,你一开始在底部,每次可以向上迈最多 K 级台阶(最少 1 级),问到达第 N 级台阶有多少种不同方式. 输入输出格式 输入格式: 两个正整数N,K. 输出格式: 一个正整数 ...
- 51Nod:1265 四点共面
计算几何 修改隐藏话题 1265 四点共面 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注 给出三维空间上的四个点(点与点的位置均不相同),判断这4个点 ...
- 部署tomcat到Linux
1. alt+p 放文件 2.解压到自定义 apps文件夹中 tar -zxvf apache-tomcat-7.0.68.tar.gz -C apps 3.进入文件启动tomcat/bin ./ ...
- 做Global Admin
globaladmin.4budget@nokia.com 10:22 https://ultima.int.net.nokia.com/eedb/Solutions/tools/ManageUser ...