在本文中,我们将介绍如何使用 Spring Boot 上传文件并通过 Postman 测试接口。我们会基于以下接口作为示例:
Boolean importDevicePushConfig(@RequestParam("file") MultipartFile file,DevicePushConfig devicePushConfig);该接口用于接收一个文件(file)和一个实体对象(devicePushConfig)的参数,其中文件通过请求体中的 form-data 方式上传,实体对象通过 URL 的查询参数传递。
@RequestParam("file") MultipartFile file
Spring 提供的 MultipartFile 是用于接收上传文件的接口。
通过 @RequestParam 注解指定参数名为 file,映射 HTTP 请求中 form-data 的对应字段。
DevicePushConfig devicePushConfig
这是一个普通的 Java 对象,接收通过 URL 参数传递的值。Spring Boot 会根据参数名和对象的字段名自动进行绑定。
DevicePushConfig 实体类public class DevicePushConfig {
@ApiModelProperty("推送系统")
private String systemCode;
@ApiModelProperty("设备编码")
private String deviceCode;
@ApiModelProperty("设备类型")
private String deviceType;
@ApiModelProperty("开始日期")
@JSONField(format = "yyyy-MM-dd")
private LocalDate startDate;
@ApiModelProperty("结束日期")
@JSONField(format = "yyyy-MM-dd")
private LocalDate endDate;
}import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/api")
public class FileUploadController {
@PostMapping("/importDevicePushConfig")
public Boolean importDevicePushConfig(@RequestParam("file") MultipartFile file,DevicePushConfig devicePushConfig) {
// 打印文件信息
System.out.println("上传的文件名称:" + file.getOriginalFilename());
System.out.println("文件大小:" + file.getSize() + " 字节");
// 打印 devicePushConfig 信息
System.out.println("DevicePushConfig 参数:" + devicePushConfig);
// 假设文件处理和配置更新成功
return true;
}
}http://localhost:8080/importDevicePushConfigContent-Type 为 multipart/form-data

file(对应 @RequestParam("file") 中的名称)

点击 Send 发送请求,接口会:
DevicePushConfig 对象。true,表示处理成功。MultipartFileSpring Boot 使用 MultipartResolver(多部分解析器)处理上传的文件。
MultipartFile 是 Spring 提供的接口,允许我们读取文件的内容和元数据。
工作流程:
multipart/form-data 格式上传文件。Content-Type 头部识别请求为多部分请求。MultipartFile 对象。核心机制:Spring MVC 的数据绑定
DevicePushConfig 的字段名匹配查询参数。setter 方法赋值。null 或基本类型的默认值)。Spring Boot 在接收 multipart/form-data 格式的请求时,会自动识别表单中的字段:
MultipartFile 对象。通过以上步骤,我们实现了一个文件上传和参数绑定的接口,并使用 Postman 进行了测试。 在实践中,确保以下几点:
@RequestParam 名称保持一致。