SoFunction
Updated on 2025-03-09

Upload file instance in Spring MVC

Several things to pay attention to when uploading files in SpringMVC:
1. Form's enctype="multipart/form-data", this is necessary to upload files.
2. Configuration:

Copy the codeThe code is as follows:

<!-- When uploading files by SpringMVC, you need to configure the MultipartResolver processor -->
<bean class="">
    <property name="defaultEncoding" value="UTF-8"/>
<!-- Specifies that the total size of the uploaded file cannot exceed 200KB. Note that the maxUploadSize property limit is not for a single file, but for the sum of the capacity of all files -->
    <property name="maxUploadSize" value="200000"/>
<!-- Maximum memory size (10240)-->
    <property name="maxInMemorySize" value="40960" />
</bean>
  
<!-- SpringMVC will throw --> when the upload file limit is exceeded.
<!-- This exception was thrown by SpringMVC when checking uploaded file information, and it has not entered the Controller method at this time -->
<bean class="">
    <property name="exceptionMappings">
        <props>
<!-- When encountering a MaxUploadSizeExceededException exception, it will automatically jump to /WEB-INF/jsp/error_fileupload.jsp page -->
            <prop key="">error_fileupload</prop>
        </props>
    </property>
</bean>

Form page for uploading/WEB-INF/jsp/

Copy the codeThe code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
<html>
    <head>
        <script type="text/javascript" src="../js/jquery-1.7."></script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload pictures</title>
    </head>
    <body>
        <form action="<%=()%>/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 picture"/>
        </form>
    </body>
</html>

Prompt page when uploading file content is too large/WEB-INF/jsp/error_fileupload.jsp

Copy the codeThe code is as follows:

<%@ page language="java" pageEncoding="UTF-8"%>
<h1>The file is too large, please reselect</h1>

The core UploadController class for uploading files

Copy the codeThe code is as follows:

package ;
 
import ;
 
import ;
 
import ;
import ;
import ;
import ;
 
/**
* Upload pictures
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
 
    @RequestMapping("/toUpload")
    public String toUpload() {
        return "/upload";
    }
 
    /***
* Save the file
     *
     * @param file
     * @return
     */
    private boolean saveFile(HttpServletRequest request, MultipartFile file) {
// Determine whether the file is empty
        if (!()) {
            try {
// Saved file path (if you are using the Tomcat server, the file will be uploaded to the \\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\\\ folder)
                String filePath = ().getServletContext()
                    .getRealPath("/") + "upload/" + ();
                File saveDir = new File(filePath);
                if (!().exists())
                    ().mkdirs();
                
// Transfer file
                (saveDir);
                return true;
            } catch (Exception e) {
                ();
            }
        }
        return false;
    }
 
    /**
* Upload pictures
     *
     * @param files
     * @param request
     * @return
     */
    @RequestMapping("/filesUpload")
    public String filesUpload(@RequestParam("myfiles") MultipartFile[] files,
            HttpServletRequest request) {
        if (files != null && > 0) {
            for (int i = 0; i < ; i++) {
                MultipartFile file = files[i];
// Save the file
                saveFile(request, file);
            }
        }
        
// Redirect
        return "redirect:/upload/toUpload";
    }
 
}

Uploading and development of this file is over.

Some commonly used methods of 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, unit byte
boolean isEmpty() //Is it empty
void transferTo(File dest) //Save to a target file