需求:在修改商品页面,添加上传商品图片功能。

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)-上传图片的更多相关文章

  1. 【SpringMVC学习10】SpringMVC对RESTfull的支持

    RESTful架构,就是目前流行的一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以正得到越来越多网站的采用.RESTful架构对url进行规范,写RESTful格式的url是什么样子 ...

  2. SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传

    SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可 ...

  3. springmvc学习笔记(10)-springmvc注解开发之商品改动功能

    springmvc学习笔记(10)-springmvc注解开发之商品改动功能 标签: springmvc springmvc学习笔记10-springmvc注解开发之商品改动功能 需求 开发mappe ...

  4. SpringMVC学习系列-后记 结合SpringMVC和Hibernate-validator,根据后台验证规则自动生成前台的js验证代码

    在SpringMVC学习系列(6) 之 数据验证中我们已经学习了如何结合Hibernate-validator进行后台的数据合法性验证,但是通常来说后台验证只是第二道保险,为了更好的用户体验会现在前端 ...

  5. springmvc学习笔记--REST API的异常处理

    前言: 最近使用springmvc写了不少rest api, 觉得真是一个好框架. 之前描述的几篇关于rest api的文章, 其实还是不够完善. 比如当遇到参数缺失, 类型不匹配的情况时, 直接抛出 ...

  6. springmvc学习笔记(简介及使用)

    springmvc学习笔记(简介及使用) 工作之余, 回顾了一下springmvc的相关内容, 这次也为后面复习什么的做个标记, 也希望能与大家交流学习, 通过回帖留言等方式表达自己的观点或学习心得. ...

  7. springmvc学习总结(二) -- maven+springmvc+spring+mybatis+mysql详细搭建整合过程讲解

    @_@ 写在最前 之前分享过下面这几篇: mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(上)(附demo和搭建过程遇到的问题解决方法) myba ...

  8. springMVC 学习笔记(一):springMVC 入门

    springMVC 学习笔记(一):spring 入门 什么是 springMVC springMVC 是 spring 框架的一个模块,springMVC 和 spring 无需通过中间整合层进行整 ...

  9. (转)SpringMVC学习(五)——SpringMVC的参数绑定

    http://blog.csdn.net/yerenyuan_pku/article/details/72511611 SpringMVC中的参数绑定还是蛮重要的,所以单独开一篇文章来讲解.本文所有案 ...

随机推荐

  1. C++ error C2440: “类型转换” : 无法从“std::vector::iterator”转换为“

    原文地址:http://blog.csdn.net/onlyou930/article/details/5602654 圆环套圆环之迭代器 话说这一日是风平浪静,万里乌云,俺的心情好的没得说,收到命令 ...

  2. Beta阶段第1周/共2周 Scrum立会报告+燃尽图 05

    作业要求与 [https://edu.cnblogs.com/campus/nenu/2018fall/homework/2284] 相同 版本控制:https://git.coding.net/li ...

  3. 玩转树莓派:OpenHAB的入门(二)

    通过第一篇的介绍,我们现在已经安装了OpenHAB和Demo House,那么接下来我们来看一下OpenHAB是如何工作的. OpenHAB如何工作? 接下来你会在openHAB配置的共享文件夹看到s ...

  4. 使用 Git & Repo 下载代码

    客户端安装 Git 安装 git,gitk 网络连接正常的情况下: $ sudo apt-get install git-core gitk git-gui 不能上网,有.deb安装包的,请执行: $ ...

  5. layer弹出相册层

    如果想要制作一个简单的相册,可以采用这个插件的方法.如果你的图片是从后台传过来的json格式里,可以通过ajax加载让图片显示在页面上,然后在使用layer插件,做出点击以后就可以查看大图的效果. 一 ...

  6. WEB接口测试之Jmeter接口测试自动化 (三)

    接口测试与数据驱动 1简介 数据驱动测试,即是分离测试逻辑与测试数据,通过如excel表格的形式来保存测试数据,用测试脚本读取并执行测试的过程. 2 数据驱动与jmeter接口测试 我们已经简单介绍了 ...

  7. Vue 之axios获取Http响应头

    服务器端:Access-Control-Expose-Headers : 'Authorization' 客户端:res.headers.Authorization 引用链接:https://segm ...

  8. GPIO口的输入输出模式

    1.浮空输入  GPIO_Mode_IN_FLOATING       2.带上拉输入  GPIO_Mode_IPU       3.带下拉输入  GPIO_Mode_IPD       4.模拟输入 ...

  9. Plotly绘图工具(多用于统计)

    作者:桂. 时间:2017-04-23  23:52:14 链接:http://www.cnblogs.com/xingshansi/p/6754769.html 前言 无意中考到一个小工具,网址为: ...

  10. Linux部署禅道Steps&Q&A

    1.查看Linux的位数: getconf LONG_BIT 结果:32/64 2. 禅道开源版安装包下载 Linux 64位 下载站点1: http://sourceforge.net/projec ...