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.

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Add an html file under resources/templates:

<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
<div>
    <form method="POST" enctype="multipart/form-data" action="/upload/uploadfile">
        <table>
            <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>
        </table>
    </form>
</div>
</body>
</html>

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

@Controller
@RequestMapping("upload")
public class UploadFileController {
    @GetMapping("/file")
    public String file(Model model){
        model.addAttribute("message", "test");
        return "file";
    }
    @PostMapping("/uploadfile")
    @ResponseBody
    public Object uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        File file1 = new File("/tmp/abc.log");
        file.transferTo(file1);
        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);
                i++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(bufReader != null) {
                bufReader.close();
            }
            if(inReader != null) {
                inReader.close();
            }
            if(in != null) {
                in.close();
            }
        }
        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