1.配置虚拟路径
2.依赖jar包
commons-io-2.4.jar
commons-fileupload-1.2.2.jar
form表单添加属性: enctype="multipart/form-data">
3.在springmvc.xml配置文件中配置多媒体文件解析器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.oranges.controller"/>
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.oranges.converters.DateConverter"></bean>
</set>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean class="com.oranges.exception.GlobalExceptionResolver"/>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
</beans>
4.上传文件
public String saveEmploy(MultipartFile photo) throws IOException {
String name = UUID.randomUUID().toString();
String oriName = photo.getOriginalFilename();
String ext = oriName.substring(oriName.lastIndexOf("."));
photo.transferTo(new File("D:\\picture\\" + name + ext));
employService.saveEmploy(employ);
return "redirect:findEmployList.do";
}