【SpringBoot】文件上传

一、使用方法

HTML ——

指定type类型为 file type="file"
若是一次性上次多个文件,后面加上 multiple

	<div class="form-group">
	  <label for="exampleInputFile">头像</label>
	  <input type="file" name="headerImg" id="exampleInputFile">
	  <p class="help-block">Example block-level help text here.</p>
	</div>
	<div class="form-group">
	  <label for="exampleInputFile">生活照</label>
	  <input type="file" name="photos" multiple>
	  <p class="help-block">Example block-level help text here.</p>
	</div>

Controller ——

1. 取得用户上传的文件

使用 @RequestPart("前端定义的文件名") MultipartFile 前端定义的文件名 取得用户上次的文件

若是接收多个文件,则使用 MultipartFile[] 数组形式接收

2. 将接收到的文件上传到某个位置

通过 MultipartFile 提供的 transferTo 方法 (要注意判断文件是否为空)

示例代码:

@Slf4j
@Controller
public class FormTestController {

    @GetMapping("/form_layouts")
    public String from_layouts(){
        return "form/form_layouts";
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email, @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {

        log.info("上传文件的信息: email={}, username={}, headerImg={}, photos={}", email, username, headerImg.getSize(), photos.length);

        if(!headerImg.isEmpty()){
            // 保存到文件服务器,OSS 服务器

            String originalFilename = headerImg.getOriginalFilename();
            // 将文件传输到某个地方
            headerImg.transferTo(new File("D:\\" + originalFilename));
            if(photos.length > 0){
                for (MultipartFile photo : photos){
                    if(photo.isEmpty()){
                        headerImg.transferTo(new File("D:\\" + photo));
                    }
                }
            }
        }

        return "main";
    }
}

二、解决文件大小超过最大长度问题

原理——

SpringBoot关于文件参数的信息被定义在 MultipartProperties.class 中,通过进入 MultipartProperties.class 查看,可以观察到单个文件上传的大小不能超过 1MB 并且总请求上传的文件大小和不能超过 10MB。

在这里插入图片描述
通过查看 MultipartAutoConfiguration.class ,可以找到对文件参数进行修改的方式为通过配置 spring.servlet.multipart 调整固定参数,具体操作如下:

解决方式——

在 application.properties 文件中加入如下代码:

spring.servlet.multipart.max-file-size=10MB #将最大文件大小改为 10MB
spring.servlet.multipart.max-request-size=100MB #将总大小改为100MB
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值