SpringBoot实现多文件上传

本文介绍了如何在SpringBoot中实现多文件上传。首先创建一个HTML表单用于上传,然后在控制器中处理请求,接收多文件并保存到指定路径。同时,文章还提到如何设置文件上传的最大容量,以避免超出限制的错误。

1. 先写一个html页面用来上传表单

我使用了一点thymeleaf,不了解无视即可。上传多文件和单文件都是用file类型提交,多文件需要指定为multiple,接受时指定参数类型即可。

<!--upload.html-->
<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form role="form" method="post" th:action="@{/upload}" 
	enctype="multipart/form-data">
    email:<input type="email" name="email"><br>
    name:<input type="text" name="name"><br>
    <input type="file" name="file"><br>
    <input type="file" name="files" multiple><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

2. 控制器处理请求

使用MultipartFile[]接受多文件类型,最后用增强for循环遍历写出,写出使用transferTo方法。

package com.yhr.boot04.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@Controller
public class upLoadController {
    @GetMapping("/begin")
    public String login(){
        return "upload";
    }

    @PostMapping("/upload")
    public void upload(@RequestParam("email") String email,
                         @RequestParam("name") String name,
                         @RequestPart("file") MultipartFile file,
                         @RequestPart("files") MultipartFile[] files) throws IOException {
        System.out.println(email + "," + name);
        if(!file.isEmpty()){
            //文件名
            String originalFilename = file.getOriginalFilename();
            //springboot独特的写出操作,很方便
            file.transferTo(new File("D:\\"+originalFilename));
        }
        if(files.length > 0){
            //遍历文件
            for (MultipartFile multipartFile : files) {
                if(!multipartFile.isEmpty()){
                    String originalFilename = multipartFile.getOriginalFilename();
                    multipartFile.transferTo(new File("D:\\"+originalFilename));
                }
            }
        }
    }
}

3. 示例

按住shift选择两个文件
在这里插入图片描述
控制台打印email和name
在这里插入图片描述
成功将文件放入D盘中

在这里插入图片描述

4. 设置容量大小

如果报错提示:org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
那么就可以在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、付费专栏及课程。

余额充值