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\
中:
成功…