在页面form中提交enctype=”multipart/form-data”的数据时,需要springmvc对multipart类型的数据进行解析,在springmvc.xml中配置multipart类型的解析器
springmvc.xml
<!--文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置上传文件的最大尺寸为5mb-->
<property name="maxUpLoadSize">
<value>5242880</value>
</property>
</bean>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
在服务器创建图片文件目录用来保存图片(配置服务器虚拟目录)
tomcat
conf/server.xml
<!--添加虚拟目录-->
<Context docBase="x:\xxx\xxx\xxx" path="/pic" reloadable="false"/>
在虚拟目录中,一定要将图片分级创建(提高i/o性能),一般按照日期创建
@RequestMapping("/xxx")
public String editItems(MulitpartFile items_pic){
//原始名称
String originalFilename = item_pic.getOriginalFilename();
//上传图片
if(items_pic!=null&&originalFilename!=null&&originalFilename.length()>0){
//存储路径
String pic_path = "x:\\xx\\xx\\xx";
//新名称
String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexof("."));
File newFile = new File(pic_path+newFileName);
//将内存中的图片写入
items_pic.transferTo(newFile);
//将新的图片名称写入数据库
}
}