Spring Boot basic study notes 14: realize file upload function

Zero, learning goals

  1. Master the use of Spring Boot to realize file upload function

1. Overview of file upload

When developing web applications, file upload is a very common requirement. The browser passes the file to the server in the form of a stream in the form of a form, and the server parses and processes the uploaded data. The file upload in Spring Boot is similar to the Spring MVC framework.

Second, realize the file upload function

(1) Create a Spring Boot project

  • Create FileUploadDemo project, add Web and Thymeleaf dependencies
    Insert picture description here
    Insert picture description here
    Insert picture description here
    Insert picture description here

(2) Integrate Bootstrap

  • Copy the bootstrap-4.0.0 in the resources/static of the 11th lecture project SpringMvcDemo2021 to the corresponding location of the current project
    Insert picture description here
    Insert picture description here

Insert picture description here

(3) Write file upload page

  • Create a file upload page in the templates directory-fileupload.html
    Insert picture description here
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link th:href="@{/bootstrap-4.0.0/css/bootstrap.css}" rel="stylesheet"></link>
    <script th:src="@{/bootstrap-4.0.0/js/jquery-3.4.1.min.js}"></script>
    <script th:src="@{/bootstrap-4.0.0/js/bootstrap.bundle.js}"></script>
    <script th:src="@{/bootstrap-4.0.0/js/bootstrap.js}"></script>
    <script>
        function add() {
     
     
            var innerDiv = "<div>";
            innerDiv += "<input type='file' name='files' required='required' class='m-2'/>"
            innerDiv += "<input type='button' value='删除' οnclick='remove(this)'/>"
            innerDiv += "</div>";
            $("#file").append(innerDiv);
        }

        //删除整个文件上传div包括2个input
        function remove(obj) {
     
     
            $(obj).parent().remove();
            //$(obj).remove();// 仅删除按钮
        }

    </script>
</head>
<body>
<div class="col-xl-6 m-auto text-lg-left bg-info pt-3 pl-5">
    <div th:if="${uploadMsg}" th:text="${uploadMsg}" class="m-2 text-danger">恭喜,上传成功!</div>
    <form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data">
        上传文件&nbsp;&nbsp;<input th:type="button" th:value="添加文件" th:onclick="add()" class="m-2"/>
        <div th:text="文件上传区域" id="file"></div>
        <input th:type="submit" value="上传" class="bg-info btn bg-warning m-2"/>
    </form>
</div>
</body>
</html>
  • The form method must be usedpost
  • The form enctype must bemultipart/form-data
    Insert picture description here

(4) Compile project configuration files

Insert picture description here

#thymeleaf配置
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.prefix=classpath:/templates/

#文件上传配置
#可多文件上传
spring.servlet.multipart.enabled=true
#单个文件大小50M
spring.servlet.multipart.max-file-size=52428800
#总文件大小300M
spring.servlet.multipart.max-request-size=314572800
  • Note that the size of the configuration file upload file is not a unit of M, but Byte
  • 50M = 50 * 1024 * 1024 B= 52428800 B
  • 300M = 300 * 1024 * 1024 B = 314572800 B

(5) Write a file upload controller

Insert picture description here

package net.hw.lesson14.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 功能:文件上传控制器
 * 作者:华卫
 * 日期:2021年02月28日
 */
@Controller
public class FileUploadController {
    
    
    @RequestMapping("/toFileUpload")
    public String toUpload(HttpServletRequest request, Model model) {
    
    
        return "fileupload";
    }
    
    @RequestMapping("/uploadFile")
    public String fileUpload(MultipartFile[] files, Model model, HttpServletRequest request) {
    
    
        // 定义上传目录
        File dir = new File("D://upload");
        try {
    
    
            if (!dir.exists()) {
    
    
                dir.mkdir();
            }
            for (int i = 0; i < files.length; i++) {
    
    
                MultipartFile file = files[i];
                String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
                InputStream in = file.getInputStream();
                FileOutputStream out = new FileOutputStream(new File(dir, filename));
                byte[] b = new byte[1024];
                int len;
                while ((len = in.read(b)) != -1) {
    
    
                    out.write(b, 0, len);
                }
                in.close();
                out.close();
                model.addAttribute("uploadMsg", "恭喜,文件上传成功!");
            }
        } catch (Exception e) {
    
    
            System.out.println(e.getMessage());
        }
        return "fileupload";
    }
}

Insert picture description here

(6) Start the application and test the effect

  • accesshttp://localhost:8080/uploadFile
    Insert picture description here
  • View the successfully uploaded files
    Insert picture description here
  • Modify the code of the uploadFile method of the file upload controller
    Insert picture description here
  • Start the application and test the effect
    Insert picture description here

3. After class development exercises-control the type of uploaded files

  1. It can String contentType = file.getContentType();be judged by the contentType ( ) of the uploaded file , and the file that meets the requirements is written to the disk, otherwise an error message will be fed back.
  2. If the file exceeds the specified size, it can also be judged in the controller, and then a friendly prompt will be given to the front desk.
  3. The front desk can also use js to make a preliminary judgment before submitting the form.

Guess you like

Origin blog.csdn.net/howard2005/article/details/114238918