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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值