- 配置虚拟目录
- 导入jar包(commons-fileupload和commons-io包)
- 在springmvc.xml中配置上传解析器
- 前端页面的修改
- 书写文件上传方法(参数类型为MultipartFile)
具体细节
1. 在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
<Context docBase="D:\develop\upload" path="/upload" reloadable="false"/>
2.
<!-- 文件上传解析器,id名称一定为multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 可对文件上传大小做限制,具体属性可以查看 如5M=1024*1024*5-->
<property name="maxUploadSize" value="5242880"></property>
</bean>
3.
<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>
<!-- 另外,form表单处还要设置 enctype="multipart/form-data" --!>
<form id="itemForm" action="${pageContext.request.contextPath}/updateItem" method="post" enctype="multipart/form-data">
5.
@RequestMapping(value = {"/updateItem"})
//pictureFile要和前端name属性同名!!!
public String updateItem(Items item, MultipartFile pictureFile) throws IllegalStateException, IOException {
//使用uuid为命名防止文件名重复
String uuidName = UUID.randomUUID().toString();
uuidName = uuidName.replaceAll("-", "");
//获取文件名
String originalFilename = pictureFile.getOriginalFilename();
//获取文件名后缀
String pexfix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
//文件上传方法,设置上传的路径,并拼接文件名和后缀
pictureFile.transferTo(new File("/Users/fatah/Desktop/upload/" + uuidName + pexfix));
//文件已上传到服务器指定位置,将文件名保存到数据库字段中
item.setPic(uuidName + pexfix);
//执行更新操作
this.itemsService.toUpdate(item);
return "redirect:/itemEdit?id=" + item.getId();
}