Using spring MVC to upload files

Keywords: Programming Java Spring Apache network

Original address: http://www.yiidian.com/springmvc/file-upload.html

File upload is a common requirement in the presentation layer. In Spring MVC, the common file upload tool of Apache is used to complete file upload and encapsulate it, making it more convenient for developers to use. Let's see how to develop it?

1 import common file upload package

<!-- commons-fileUpload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

2 profile resolver

<! -- profile upload parser
 Note: id must be configured and name must be multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <! -- configuration limit file upload size (in bytes) -- >
    <property name="maxUploadSize" value="1024000"/>
</bean>

Pay attention to several points:

  • CommonsMultipartResolver resolver must be configured
  • The resolver id must be called multipartResolver, otherwise the file cannot be received successfully
  • You can limit the file upload size through the maxUploadSize property

3 design file upload form

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>A little tutorial network-File upload</title>
</head>
<body>
<h3>SpringMVC Method file upload</h3>
<form action="/upload" method="post" enctype="multipart/form-data">
    Select File:<input type="file" name="imgFile"> <br/>
    Document description:<input type="text" name="memo"> <br/>
    <input type="submit" value="upload">
</form>
</body>
</html>

Notice the following points when uploading the form:

enctype of form must be changed to multipart / form data Form submission method must be POST, not GET

4 write the receiving documents and parameters of the controller

package com.yiidian.controller;
import com.yiidian.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 *  Demonstrate Spring MVC file upload
 * A little tutorial - www.yidian.com
 */
@Controller
public class UploadController {

    /**
     * receive files
     */
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, MultipartFile imgFile,String memo){
        //1. Get the path of the website's upload directory: ServletContext object
        String upload = request.getSession().getServletContext().getRealPath("/upload");

        //Determine whether the directory exists, does not exist, create by yourself
        File uploadFile = new File(upload);
        if(!uploadFile.exists()){
            uploadFile.mkdir();
        }

        //Save the file to the upload directory

        //2. Generate random file name
        //2.1 original file name
        String oldName = imgFile.getOriginalFilename();

        //2.2 randomly generated file name
        String uuid = UUID.randomUUID().toString();
        //2.3 get file suffix
        String extName = oldName.substring(oldName.lastIndexOf(".")); //.jpg

        //2.4 final file name
        String fileName = uuid+extName;

        //3. preservation
        try {
            imgFile.transferTo(new File(upload+"/"+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Document description:"+memo);

        return "success";

    }
}

Note: here, the MultipartFile object is used to receive the file, and the file is stored in the upload directory of the project, and common parameters are also received.

5 running test

Check the target directory of the project for files

Content of console output parameters:

Source code download: https://pan.baidu.com/s/1mtuGCnL_aoq0IEem_viwMg

Welcome to my official account: a little tutorial. Get exclusive learning resources and daily dry goods push. If you are interested in my series of tutorials, you can also follow my website: yiidian.com

Posted by enoyhs on Wed, 04 Mar 2020 05:04:44 -0800