1、给Tomcat配置虚拟路径
目的:当图片上传到Tomcat的项目中后,eclipse中源码项目中并没有该图片;此时,通过eclipse重启Tomcat后,Tomcat中的项目会与eclipse中的项目同步,这时候上传的图片就会消失。所以为了避免开发的时候频繁的保存上传到Tomcat的图片,为Tomcat配置一个虚拟路径用来保存图片。
(1)方式一
tomcat下conf/server.xml中添加:
<Context docBase="D:\develop\upload\temp" path="/pic" reloadable="false"/>
(2)方式二
在eclipse中配置
配置虚拟路径后,开启服务器,就可以访问到该路径下的文件
2、步骤
(1)导入jar包
(2)jsp页面
Form表单必须添加属性:enctype="multipart/form-data"
图片name必须和controller形参名相同
<form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${item.name }" /></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${item.price }" /></td>
</tr>
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime"
value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>" /></td>
</tr>
<tr>
<td>商品图片</td>
<td>
<c:if test="${item.pic !=null}">
<img src="/pic/${item.pic}" width=100 height=100/>
<br/>
</c:if>
<input type="file" name="pictureFile"/>
</td>
</tr>
<tr>
<td>商品简介</td>
<td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交" />
</td>
</tr>
</table>
</form>
(3)controller
FilenameUtils是Commons.io的一个工具类,getExtension()方法可以从字符串中截取文件后缀名,MultipartFile 是一个接口。
@RequestMapping(value="/updateitem.action")
public String updateItem(Items item, MultipartFile pictureFile, Model model) throws Exception {
//获得文件后缀名
String extension = "." + FilenameUtils.getExtension(pictureFile.getOriginalFilename());
//设置图片名
String picName = UUID.randomUUID().toString() + extension;
item.setPic(picName);
//保存图片
pictureFile.transferTo(new File("H:\\upload\\" + picName));
ItemService.updateItem(item);
return "redirect:/item/itemlist.action";
}
(4)配置上传解析器
<!-- 图片解析器,name固定,不能为其他值,因为springmvc是根据该值注入对象的 -->
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件最大值:5M=5*1024*1024 -->
<property name="maxUploadSize" value="5242880"/>
</bean>