Spring MVC基础之文件上传

Spring MVC基础之文件上传

1、使用IDEA构建项目如下:

在这里插入图片描述

2、代码

index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form:form enctype="multipart/form-data" action="/day0901/login.action" commandName="studentModel" modelAttribute="studentModel">
    姓名:<form:input path="studentName" /><form:errors path="studentName" /> <br>
    密码:<form:input path="password"/><form:errors path="password" /><br>
    请选择需要上传的文件:<input type="file" name="file" /><form:errors path="file" /><br>
    <input type="submit" value="提交" />
  </form:form>
  </body>
</html>

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h4>上传成功...</h4>
</body>
</html>

FileController.java

package my.controller;
import my.model.StudentModel;
import my.validator.FileValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.File;
import java.io.IOException;
@Controller
public class FileController {
    @Autowired
    @Qualifier("studentModel")
    private StudentModel studentModel;
    @Autowired
    @Qualifier("fileValidator")
    private FileValidator validator;

    //定位到首页:index.jsp
    @RequestMapping(value = "/index.action",method = RequestMethod.GET)
    public String index(Model model)  {
        model.addAttribute("studentModel",studentModel);
        return "index";
    }

    /**
     * 1、之前在文本框<form:input />的写法是需要定义一个入口的model然后转到首页:
     *
     *  @AutoWired
     *  @Qualifier("studentModel")
     *  private StudentModel studentModel;
     *
     *  //定位到首页:index.jsp
     *  @RequestMapping(value = "/index.do")
     *  public ModelAndView index(@ModelAttribute("student") Student student){
     *      return new ModelAndView("index","student",new Student());
     *  }
     *
     *  @ModelAttribute(value="studenModel")
     *  public StudentModel createModel{
     *      return studentModel;
     *  }
     *2、但是有校验器就不需要再定义一个model了,因为校验器会自动绑定model,只需要:
     *  //定位到首页:index.jsp
     *  @RequestMapping(value = "/index.action",method = RequestMethod.GET)
     *  public String index(Model model)  {
     *      model.addAttribute("studentModel",studentModel);
     *      return "index";
     *  }
     *  然后需要一个@Validated注解申明model
     *
     * */

    //绑定校验器
    @InitBinder
    public void initBinder(DataBinder binder){
        binder.setValidator(validator);
    }

    //定位到结果打印页面:result.jsp
    @RequestMapping(value = "/login.action",method = RequestMethod.POST)
    public String result(@Validated StudentModel studentModel, Errors errors) throws IOException {
        if(errors.hasErrors()){
            System.out.println(errors.getErrorCount());
            return "index";
        }else{
            //定义一个指定的上传路径和文件名
            File filepath = new File("C:\\test\\"+studentModel.getFile().getOriginalFilename());
            //开始上传
            FileCopyUtils.copy(studentModel.getFile().getBytes(), filepath);
            //上传完成
            return "/pages/result";
        }
    }
}

FileValidator.java

package my.validator;
import my.model.StudentModel;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class FileValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return StudentModel.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors,"studentName",null,"姓名不得为空...");
        ValidationUtils.rejectIfEmpty(errors,"password",null,"密码不得为空...");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors,"file",null,"文件不得为空...");
    }
}

StudentModel.java

package my.model;
import org.springframework.web.multipart.MultipartFile;
public class StudentModel {
    private String studentName;
    private String password;
    private MultipartFile file;

    public StudentModel(String studentName, String password, MultipartFile file) {
        this.studentName = studentName;
        this.password = password;
        this.file = file;
    }

    public StudentModel() { }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    @Override
    public String toString() {
        return "StudentModel{" +
                "studentName='" + studentName + '\'' +
                ", password='" + password + '\'' +
                ", file=" + file +
                '}';
    }
}

dispatcher-servlet.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="my.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="studentModel" class="my.model.StudentModel"/>
    <bean id="fileValidator" class="my.validator.FileValidator"/>

    <!--开启对文件上传的支持-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--编码过滤器-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
3、运行

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
最后我们看下是否则真的上传到了指定文件夹C:\test\中:
在这里插入图片描述
成功…

发布了49 篇原创文章 · 获赞 38 · 访问量 8313

猜你喜欢

转载自blog.csdn.net/Mr_C_python/article/details/100124877