Spring MVC文件上传示例

时间:2020-02-23 14:35:55  来源:igfitidea点击:

Spring MVC使用Apache Common FileUpload API来上载文件。
在Spring MVC中配置文件上传非常容易。

Spring MVC文件上传示例的步骤:

1)使用名为"springmvcfileupleadexample"的Maven创建动态Web项目。

2)Maven依赖性

它需要Spring依赖,因为我们在Spring MVC Hello World示例中。
它也需要apache common io jars,因此我们需要跟上依赖它。

<!-- Apache Common io dependencies -->
  <!-- Apache Commons FileUpload -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>
 
  <!-- Apache Commons IO -->
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

所以pom.xml如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>org.igi.theitroad</groupId>
 <artifactId>SpringMVCFileUploadExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringMVCFileUploadExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>
  <!-- Spring dependency -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
 
  <!-- Apache Common io dependencies -->
  <!-- Apache Commons FileUpload -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>
 
  <!-- Apache Commons IO -->
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>SpringMVCFileUploadExample</finalName>
 
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>
 
 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
 
</project>

3)创建模型,控制器和验证器

在packge org.igi.theitroad.model中创建一个名为"fileupload.java"的类模型.model。

package org.igi.theitroad.model;
import org.springframework.web.multipart.MultipartFile;
 
public class FileUpload {
 
 MultipartFile file;
 
 public MultipartFile getFile() {
  return file;
 }
 
 public void setFile(MultipartFile file) {
  this.file = file;
 }
}

在package org.igi.theitroad.Controller中创建类fileuploadcontroller.java。
它是Spring 控制器,要了解更多控制器,请通过Spring MVC Hello World示例。

package org.igi.theitroad.controller;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import org.igi.theitroad.model.FileUpload;
import org.igi.theitroad.validator.FileUploadValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class FileUploadController {
 
 @Autowired
 FileUploadValidator fileValidator;
 
 @RequestMapping("/fileUploadForm")
 public ModelAndView getUploadForm(
   @ModelAttribute("uploadedFile") FileUpload uploadedFile,
   BindingResult result) {
  return new ModelAndView("fileUploadForm");
 }
 
 
 //When click on submit, below method will get called
 @RequestMapping("/submitFileUpload")
 public ModelAndView fileUploaded(
   @ModelAttribute("uploadedFile") FileUpload uploadedFile,
   BindingResult result) {
  InputStream inputStream = null;
  OutputStream outputStream = null;
 
  //Getting uploaded file
  MultipartFile file = uploadedFile.getFile();
  fileValidator.validate(uploadedFile, result);
 
  String fileName = file.getOriginalFilename();
 
  //If it has error, redirect it to same page
  if (result.hasErrors()) {
   return new ModelAndView("fileUploadForm");
  }
 
  try {
   inputStream = file.getInputStream();
 
   File newFile = new File("/Users/igi/Documents/SpringMVCUploadedFiles/" + fileName);
   if (!newFile.exists()) {
    newFile.createNewFile();
   }
   outputStream = new FileOutputStream(newFile);
   int read = 0;
   byte[] bytes = new byte[1024];
 
   while ((read = inputStream.read(bytes)) != -1) {
    outputStream.write(bytes, 0, read);
   }
  } catch (IOException e) {
   //TODO Auto-generated catch block
   e.printStackTrace();
  }
 
  return new ModelAndView("fileUploadSuccess", "fileName", fileName);
 }
 
}

我们需要验证器进行验证,例如未选择文件。
在package org.igi.theitroad.validator中创建validator fileuploadvalidator.java.java

package org.igi.theitroad.validator;
 
import org.igi.theitroad.model.FileUpload;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
 
 
public class FileUploadValidator implements Validator{
 
 @Override
 public boolean supports(Class clazz) {
  //just validate the FileUpload instances
  return FileUpload.class.isAssignableFrom(clazz);
 }
 
 @Override
 public void validate(Object target, Errors errors) {
  
  FileUpload file = (FileUpload)target;
  
  if(file.getFile().getSize()==0){
   errors.rejectValue("file", "uploadForm.selectFile",  
         "Please select a file!");
  }
 }
}

4)Spring 配置

它将在Hello World示例中具有简单的Web.xml。

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>
     <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>springmvc-dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
    </web-app>

我们需要更改"springmvc-dispatcher-servlet.xml"如下更改

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
<context:component-scan base-package="org.igi.theitroad.controller" 
 
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/JSP/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
   <!-- Validator -->
   <bean id="fileValidator" class="org.igi.theitroad.validator.FileUploadValidator"   
  
 <bean id="multipartResolver"  
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"   
 <mvc:annotation-driven
 
</beans>

我们需要在上面的文件中声明MultiPartresolver Bean,以启用文件上传。
我们还提出了验证者的bean条目。

5)观点

最后为文件上传表单和文件上传成功页面创建视图。
在/web-inf/jsp /文件夹中创建fileuploadform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<title>Spring MVC file upload</title>
</head>
<body>
 <center>
  <h2>Spring MVC file upload</h2>
  <h3>Please select a file to upload !</h3>
  
  <form:form method="post" enctype="multipart/form-data"
   modelAttribute="uploadedFile" action="submitFileUpload.htm">
   <table>
    <tr>
     <td>Upload File: </td>
     <td><input type="file" name="file" 
     </td>
     <td style="color: red; font-style: italic;"><form:errors
       path="file" 
     </td>
    </tr>
    <tr>
     <td> </td>
     <td><input type="submit" value="Upload" 
     </td>
     <td> </td>
    </tr>
   </table>
  </form:form>
 </center>
</body>
</html>

创建filuploadsuccess.jsp/web-inf/jsp /文件夹

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
 
<html>
<body>
 <h2>Spring MVC file upload example</h2>
 
 FileName : "
  ${fileName} " - Uploaded Successful.
 
</body>
</html>

6)它是Maven Build的时间

将目标作为清洁安装(如下所示),然后单击运行

7)运行应用程序

右键单击项目 - >在服务器上运行AS - >运行

选择Apache Tomcat,然后单击"完成"

我们将看到以下屏幕:URL:http://localhost:8080/springmvcfileuploadexample/fileuploadform.htm

如果直接单击"上载"按钮而不选择任何文件,则会为我们提供错误作为"选择文件"

让我们上传"config.properties"

如果文件已成功上传,我们可以检查我们在上面应用程序中给出的路径的文件夹。