SpringMVC Uploads File through commons fileupload

  • 2021-08-12 02:42:33
  • OfStack

Directory Configuration web. xmlSpringMVC Configuration File applicationContext. xml File Upload Controller Upload Implementation 1 Upload Implementation 2 Test Dependencies

Configure

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
   version="5.0">
 <!-- Registration DispatcherServlet-->
 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:applicationContext.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

SpringMVC configuration file applicationContext. xml

Core configuration class for uploading files: CommonsMultipartResolver, note id="multipartResolver" Don't make mistakes


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

 <!-- Configure automatic scanning controller Bag -->
 <context:component-scan base-package="com.pro.controller"/>
 <!-- Configuring static resource filtering -->
 <mvc:default-servlet-handler/>
 <!-- Configure annotation driver -->
 <mvc:annotation-driven/>

 <!-- Configure the view parser -->
 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <!-- Prefix -->
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <!-- Suffix -->
  <property name="suffix" value=".jsp"/>
 </bean>

 <!--SpringMVC File upload configuration -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- Format the encoding of the request ,  Must be with pageEncoding Properties of 1 To ,  So that the values of the form can be read correctly ,  Default to ISO-8859-1-->
  <property name="defaultEncoding" value="utf-8"/>
  <!-- Size limit of uploaded files ,  In bytes  (10485760 = 10M)-->
  <property name="maxUploadSize" value="10485760"/>
  <property name="maxInMemorySize" value="40960"/>
 </bean>
</beans>

File upload Controller

Upload Implementation 1


package com.pro.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {
  /*
   *  Adopt file.transferTo  To save the uploaded file 
   */
  @RequestMapping("/upload2")
  public Map fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

    // Upload path save settings 
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
      realPath.mkdir();
    }
    // Upload file address 
    System.out.println(" Upload file saving address  --> "+realPath);

    // Pass CommonsMultipartFile Write the file directly (pay attention to this time) 
    file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));

    Map<Object, Object> hashMap = new HashMap<>();
    hashMap.put("code", 0);
    hashMap.put("msg", " Upload succeeded ");

    return hashMap;
  }
}

Upload Implementation 2

The file name here does not use UUID combination name for convenience of testing


package com.pro.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {

  // @RequestParam("file")  Will  name=file  Control is encapsulated into a file obtained by the  CommonsMultipartFile  Object 
  //  Batch upload handle  CommonsMultipartFile  Just change it to an array 
  @RequestMapping("/upload")
  public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
    //  Get the file name 
    String uploadFileName = file.getOriginalFilename();

    //  If the file name is empty ,  Go directly back to the home page 
    if ("".equals(uploadFileName)) {
      return "file upload error";
    }

    System.out.println(" Upload file name  --> " + uploadFileName);


    //  Set where to save files 
    String path = request.getServletContext().getRealPath("/upload");
    //  Judge whether the path exists or not 
    File realPath = new File(path);
    if (!realPath.exists()) {
      //  Create if it does not exist 
      realPath.mkdir();
    }

    System.out.println(" File save path  --> " + realPath);

    //  Get the file input stream 
    InputStream is = file.getInputStream();
    //  Get the file output stream 
    FileOutputStream os = new FileOutputStream(new File(realPath, uploadFileName));

    //  Buffer reading and writing files 
    byte[] buffer = new byte[1024];
    int len;
    while ((len = is.read(buffer)) != -1) {
      os.write(buffer, 0, len);
      os.flush();
    }

    //  Close flow 
    os.close();
    is.close();

    return "file upload success";
  }
}

Test


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
  <title>$Title$</title>
 </head>
 <body>
  <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload2" method="post">
   <input type="file" name="file">
   <input type="submit" value=" Upload implementation 1">
  </form>
  
  
  <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post">
   <input type="file" name="file">
   <input type="submit" value=" Upload implementation 2">
  </form>
 </body>
</html>

Dependency

The core dependency is commons-fileupload


<!-- Import dependencies -->
<dependencies>
  <!-- Unit test -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
  </dependency>
  <!--spring-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
  </dependency>
  <!-- File upload -->
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
  </dependency>
  <!--servlet-api Import a higher version of -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
  </dependency>
  <!--jsp-->
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
  </dependency>
  <!--jstl Expression -->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
</dependencies>

Related articles: