Instances of uploaded files in Spring MVC

  • 2021-06-28 13:39:12
  • OfStack

SpringMVC upload file should pay attention to several points:
1. enctype="multipart/form-data" for form, which is required for uploading files
2. applicationContext.xml Configuration:


<!-- SpringMVC When uploading files, you need to configure MultipartResolver processor -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"/>
    <!-- Specifies that the total size of the uploaded file cannot exceed 200KB .Be careful maxUploadSize Attribute restrictions are not for a single file, but the sum of all file sizes -->
    <property name="maxUploadSize" value="200000"/>
    <!-- Maximum memory size (10240)-->
    <property name="maxInMemorySize" value="40960" />
</bean>
  
<!-- SpringMVC When the upload file limit is exceeded, it will be thrown org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- The exception is SpringMVC Thrown while checking for uploaded file information and has not yet entered Controller Method -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <!-- encounter MaxUploadSizeExceededException Automatically jump to when an exception occurs /WEB-INF/jsp/error_fileupload.jsp page -->
            <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
        </props>
    </property>
</bean>

Form page for upload/WEB-INF/jsp/upload.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Upload pictures </title>
    </head>
    <body>
        <form action="<%=request.getContextPath()%>/upload/filesUpload" method="POST" enctype="multipart/form-data">
            yourfile: <input type="file" name="myfiles"/><br/>
            yourfile: <input type="file" name="myfiles"/><br/>
            <input type="submit" value=" Upload pictures "/>
        </form>
    </body>
</html>

Prompt page for uploading files with too large contents/WEB-INF/jsp/error_fileupload.jsp


<%@ page language="java" pageEncoding="UTF-8"%>
<h1> File too large, please select again </h1>

Core UploadController class for uploading files


package com.ljq.web.controller.annotation;
 
import java.io.File;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
 
/**
 * Upload pictures
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
 
    @RequestMapping("/toUpload")
    public String toUpload() {
        return "/upload";
    }
 
    /***
     * Save File
     *
     * @param file
     * @return
     */
    private boolean saveFile(HttpServletRequest request, MultipartFile file) {
        // Determine if the file is empty
        if (!file.isEmpty()) {
            try {
                // Saved file path ( If you are using Tomcat Server, files will be uploaded to \\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\ In folder   )
                String filePath = request.getSession().getServletContext()
                    .getRealPath("/") + "upload/" + file.getOriginalFilename();
                File saveDir = new File(filePath);
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                
                // Dump File
                file.transferTo(saveDir);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
 
    /**
     * Upload pictures
     *
     * @param files
     * @param request
     * @return
     */
    @RequestMapping("/filesUpload")
    public String filesUpload(@RequestParam("myfiles") MultipartFile[] files,
            HttpServletRequest request) {
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                // Save File
                saveFile(request, file);
            }
        }
        
        // redirect
        return "redirect:/upload/toUpload";
    }
 
}

The file upload development is over.

Some of the methods commonly used in the MultipartFile class:
String getContentType() //Get file MIME type
InputStream getInputStream()//Return file stream
String getName () //Get the name of the file component in the form
String getOriginalFilename()//Get the original name of the uploaded file
long getSize ()//Get the byte size of the file in byte
boolean isEmpty () //Is it empty
void transferTo (File dest)//Save to a target file


Related articles: