SpringMVC实现文件上传
程序员文章站
2022-06-03 10:37:21
...
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";
}