Spring Boot upload file

To upload a Spring Boot file, you only need to set a MultipartFile parameter on the controller's method. Of course, you can use @ RequestParam to specify the method name. If you want to upload multiple files, you can use arrays. In addition, you can use a class whose member variable is MultipartFile to receive files and other parameters.
In order to demonstrate it, we need to have pages to upload files and introduce the thmeleaf template engine.


Add an html file under resources/templates:

<html xmlns:th="http://www.thymeleaf.org">
<div th:if="${message}">
    <h2 th:text="${message}"/>
    <form method="POST" enctype="multipart/form-data" action="/upload/uploadfile">
            <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
            <tr><td></td><td><input type="submit" value="Upload" /></td></tr>

Write a Controller class, one for Get page and one for printing the submitted file content.

public class UploadFileController {
    public String file(Model model){
        model.addAttribute("message", "test");
        return "file";
    public Object uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        File file1 = new File("/tmp/abc.log");
        FileInputStream in = null;
        InputStreamReader inReader = null;
        BufferedReader bufReader = null;
        try {
            in = new FileInputStream(file1);
            inReader = new InputStreamReader(in, "UTF-8");
            bufReader = new BufferedReader(inReader);
            String line = null;
            int i = 1;
            while ((line = bufReader.readLine()) != null) {
                System.out.println("The first" + i + "That's ok:" + line);
        }catch (Exception e){
        }finally {
            if(bufReader != null) {
            if(inReader != null) {
            if(in != null) {
        return "OK";

After running, upload files, and the console prints as follows:

Line 1: aaa
 Line 2: bbb
 Line 3: CC

Tags: Spring Thymeleaf

Posted on Sun, 03 May 2020 22:07:44 -0400 by tnewton