spring boot---文件上传

  1. 表单页面
 <form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
                            <div class="form-group">
                                <label for="exampleInputEmail1">邮箱</label>
                                <input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputPassword1">名字</label>
                                <input type="text" name="username" class="form-control" id="exampleInputPassword1" placeholder="Password">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputFile">头像</label>
                                <input type="file" name="headImage" id="exampleInputFile">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputFile">生活照</label>
                                <input type="file" name="photos" multiple >
                            </div>
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox"> Check me out
                                </label>
                            </div>
                            <button type="submit" class="btn btn-primary">提交</button>
                        </form>

其中, <input type="file" name="photos" multiple >multipart属性是设置其为多文件上传。
2. 文件上传代码

 @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username")String username,
                         @RequestPart("headImage") MultipartFile headImage,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
        log.info("email={},username={},headImage={},photos={}",email,username,headImage.getSize(),photos.length);
        if(!headImage.isEmpty()){
            headImage.transferTo(new File("D:\\1\\"+headImage.getOriginalFilename()));
        }
        if(photos.length>0){
            for(MultipartFile photo:photos){
                photo.transferTo(new File("D:\\1\\"+photo.getOriginalFilename()));
            }
        }
        return "main";
    }
  1. 以上代码运行可能会报如下错误。这是因为上传的文件大笑超过了设定的大小。
    在这里插入图片描述
    解决方法:
    文件上传自动配置类是:MultipartAutoConfigration,该自动配置类绑定了MultipartProperties.class属性。
    在这里插入图片描述
    所以我们需要在配置文件中application.properties中重新设置文件上传的大小限制。如下所示。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB

重新运行即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值