File upload and file download

Keywords: Front-end Spring Spring MVC


File upload is one of the most common functions in project development. Spring MVC can well support file upload, but MultipartResolver is not installed in the spring MVC context by default, so it cannot handle file upload by default. If you want to use spring's file upload function, you need to configure MultipartResolver in the context.
Front end form requirements: in order to upload files, the method of the form must be set to POST and the enctype must be set to multipart / form data. Only in this case, the browser will send the file selected by the user to the server as binary data.

Give a detailed description of the enctype attribute in the form:

  • Application / x-www = form urlencoded: by default, only the value attribute value in the form field is processed. Forms with this encoding method will process the value in the form field into URL encoding.
  • Multipart / form data: this encoding method will process form data in the form of binary stream. This encoding method will also encapsulate the contents of the file specified in the file field into the request parameters, and will not encode characters.
  • text/plain: except for converting spaces into "+" signs, other characters are not encoded. This method is applicable to sending mail directly through forms.

The file upload of spring MVC also depends on the component of Apache CommonsFileUpload.

File upload

1. If you are good at something in advance, you must first sharpen its tools and import the jar package

<!--File upload-->

2. Configure web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""


3. Configure applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:component-scan base-package="com.feng.controller"/>
    <!--solve Json Garbled code-->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>

    <!--File upload configuration-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- The encoding format of the request must be and jSP of pageEncoding Property is consistent so that the contents of the form can be read correctly. The default is ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- Maximum upload file size, in bytes (10485760)=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>

Note: note!!! For file upload configuration, the id of this bena must be: multipartResolver, otherwise an error of 400 will be reported when uploading the file!

4. Write the front-end page index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <form action="/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload">
  <a href="${pageContext.request.contextPath}/download">Click download</a>

5. Write Controller

package com.feng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;

public class FileController {
    //@RequestParam("file") encapsulates the file obtained by the name=file control into a CommonsMultipartFile object
    // If you upload CommonsMultipartFile in batch, it can be an array
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //Get file name: file.getOriginalFilename();
        String uploadFileName = file.getOriginalFilename();
        //If the file name is empty, go back to the home page directly!
        if ("".equals(uploadFileName)) {
            return "redirect:/index.jsp";
        System.out.println("Upload file name : " + uploadFileName);
        //Upload path save settings
        String path = request.getServletContext().getRealPath("/upload");
        //If the path does not exist, create one
        File realPath = new File(path);
        if (!realPath.exists()) {
        System.out.println("Upload file storage address:" + realPath);
        InputStream is = file.getInputStream();
        //File input stream
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
        //File output stream
        // Read write
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = != -1) {
            os.write(buffer, 0, len);
        return "redirect:/index.jsp";

6. Start tomcat test

Use file.Transto to save the uploaded file

1. Write controller

     * Use file.Transto to save the uploaded file
     * */
    public String 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()){
        //Upload file address
        System.out.println("Upload file storage address:"+realPath);
        //Write the file directly through the CommonsMultipartFile method (note this time)
        file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
        return "redirect:/index.jsp";

2. Front end form submission and modification address
3. Start tomcat

File download

File download steps:

  1. Set response header
  2. Read file – InputStream
  3. Write out file – OutputStream
  4. Perform operation
  5. Close flow (first on then off)

1. Write controller

package com.feng.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoad {
    public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
        //Address of the picture to download
        String path = request.getServletContext().getRealPath("/upload");
        String fileName = "1.txt";
        //1. Set response header
        //Set the page not to be cached, and clear the buffer
        //Character encoding
        //Binary transmission data
        //Set response header
        response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
        File file = new File(path,fileName);
        //2. Read file -- input stream
        InputStream input=new FileInputStream(file);
        //3. Write out file -- output stream
        OutputStream out = response.getOutputStream();
        byte[] buff =new byte[1024];
        int index=0;
        //4. Perform a write out operation
        while((index=!= -1){
            out.write(buff, 0, index);
        return null;

2. Prepare front end

<a href="${pageContext.request.contextPath}/download">Click download</a>

3. Start tomcat test

Posted by djheru on Fri, 03 Dec 2021 04:58:48 -0800