SpringMVC实现文件上传

1.配置虚拟路径

SpringMVC实现文件上传_第1张图片

2.依赖jar包
commons-io-2.4.jar
commons-fileupload-1.2.2.jar
form表单添加属性: enctype="multipart/form-data">
3.在springmvc.xml配置文件中配置多媒体文件解析器

<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>5242880value>
        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";
    }

你可能感兴趣的:(SpringMVC)