编程知识 cdmana.com

Spring MVC achieves file upload through Commons fileUpload

To 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">
    <!-- register 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 The configuration file applicationContext.xml

The core configuration class for uploading files :CommonsMultipartResolver, Be careful id="multipartResolver" Don't write wrong

<?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 package -->
    <context:component-scan base-package="com.pro.controller"/>
    <!-- Configure 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">
        <!-- Set the encoding format of the request ,  It has to be with pageEncoding The properties of are consistent ,  So that the values of the form can be read correctly ,  The default is ISO-8859-1-->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- Upload file size limit ,  The unit is byte  (10485760 = 10M)-->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>


Upload files Controller

Upload to achieve a

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 {
    /*
     *  use file.transferTo  To save the uploaded files 
     */
    @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 save address  --> "+realPath);

        // adopt 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 successful ");

        return hashMap;
    }
}

Upload implementation 2

The file name here is not used UUID Combination name For testing purposes

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")  take  name=file  Control to get a file packaged as  CommonsMultipartFile  object 
    //  Batch upload  CommonsMultipartFile  Change to 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 straight back to the home page 
        if ("".equals(uploadFileName)) {
            return "file upload error";
        }

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


        //  Set where to save the file 
        String path = request.getServletContext().getRealPath("/upload");
        //  Determine if the path exists 
        File realPath = new File(path);
        if (!realPath.exists()) {
            //  If it doesn't exist, create it 
            realPath.mkdir();
        }

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

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

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

        //  Closed 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 to achieve a ">
    </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>

rely on

The core dependence is commons-fileupload

<!-- Import dependence -->
<dependencies>
    <!-- unit testing -->
    <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>
    <!-- Upload files -->
    <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>

版权声明
本文为[jiawei3998]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/01/20210131155455415v.html

Scroll to Top