Spring Boot上傳文件

Spring Boot上傳文件只需要在controller的方法上設置一個MultipartFile 參數即可,當然可以用@RequestParam指定方法名,如果是上傳多個file時,可以使用數組,另外也可以用一個成員變量爲MultipartFile的類來接收文件和其他參數。
爲了演示它,我們需要有頁面來上傳文件,引入thymeleaf模板引擎。

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

在resources/templates下增加一個html文件:

<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>

寫一個Controller類,一個用來Get頁面,一個用來打印提交的file內容。

@Controller
@RequestMapping("upload")
public class UploadFileController {
    @GetMapping("/file")
    public String file(Model model){
        model.addAttribute("message", "測試");
        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("第" + i + "行:" + 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";
    }
}

運行之後,上傳個文件,控制檯打印如下:

第1行:aaa
第2行:bbb
第3行:Ccc
發佈了131 篇原創文章 · 獲贊 35 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章