SpringBoot实现文件上传接口

简单演示了在SpringBoot实现文件上传接口

SpringBoot实现文件上传接口

在SpringBoot中默认已集成相关依赖,所以无需额外导入

后端Controller层

使用MultipartFile接收文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {

    // 单文件上传
    @PostMapping("/upload/single")
    public String uploadSingleFile(
            @RequestParam("file") MultipartFile file,  // 接收文件,参数名需与前端一致
    		@RequestParam(value = "description", required = false) String description  // 可选的额外参数
    ) {
        // 处理文件(如保存到本地或云存储)
        if (file.isEmpty()) {
            return "文件为空";
        }
        String fileName = file.getOriginalFilename(); // 获取文件名
        // ... 具体保存逻辑
        return "上传成功:" + fileName;
    }

    // 多文件上传(参数用数组接收)
    @PostMapping("/upload/multiple")
    public String uploadMultipleFiles(
            @RequestParam("files") MultipartFile[] files  // 多文件用数组接收,参数名与前端一致
    ) {
        // 遍历处理每个文件
        // ...
        return "上传成功,共" + files.length + "个文件";
    }
}

可在application.properties中配置文件大小限制:

1
2
3
4
# 单个文件最大大小
spring.servlet.multipart.max-file-size=10MB
# 一次请求中所有文件的总大小
spring.servlet.multipart.max-request-size=50MB

前端参数与请求要求

前端需通过FormData对象构建请求,并指定正确的Content-Type

请求方式:POST

请求头Content-Type 必须设为 multipart/form-data,表示表单包含二进制数据(文件)

代码示例:

HTML表达:

1
2
3
4
5
<form action="/upload/single" method="post" enctype="multipart/form-data">
    <input type="file" name="file" /> <!-- name必须与后端参数名一致 -->
    <input type="text" name="description" placeholder="文件描述" />
    <button type="submit">上传</button>
</form>

AJAX上传:(多文件示例,使用 jQuery)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$("#uploadBtn").click(function() {
    const formData = new FormData();
    // 添加文件(files是input[type="file"]的DOM对象,multiple属性允许选择多文件)
    const files = document.getElementById("fileInput").files;
    for (let i = 0; i < files.length; i++) {
        formData.append("files", files[i]); // 键名"files"需与后端@RequestParam("files")一致
    }
    // 添加额外参数
    formData.append("description", "这是一批文件");

    $.ajax({
        url: "/upload/multiple",
        type: "POST",
        data: formData,
        contentType: false, // 必须设为false,让浏览器自动处理multipart/form-data
        processData: false, // 禁止jQuery序列化FormData(否则文件会被转为字符串)
        success: function(response) {
            console.log("上传结果:", response);
        }
    });
});

总结

  1. 后端
    • MultipartFile(单文件)或MultipartFile[](多文件)接收文件
    • @RequestParam的参数名需与前端表单 / FormData 的键名一致
    • 可配置文件大小限制
  2. 前端
    • 请求方式为POST
    • Content-Type设为multipart/form-data
    • 文件输入框的name或 FormData 的键名,必须与后端参数名匹配
    • 额外参数通过 FormData 添加,键名与后端一致
本站于2025年3月26日建立
使用 Hugo 构建
主题 StackJimmy 设计