Spring Webflux接收Excel文件报415不支持媒体类型错误求助
解决Spring Webflux上传Excel文件报415 Unsupported Media Type错误
问题根源
Spring Webflux的响应式编程栈不支持Servlet栈的MultipartFile类型,你当前用它接收application/vnd.openxmlformats-officedocument.spreadsheetml.sheet类型的文件,自然会触发415不支持媒体类型错误。响应式栈应该使用专门的FilePart或Part接口来处理文件上传。
解决方案步骤
1. 修正Controller接收参数类型
将Controller方法中的MultipartFile替换为FilePart,这是Webflux提供的响应式文件接收类型。示例代码:
import org.springframework.http.codec.multipart.FilePart; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; @RestController public class ExcelUploadController { @PostMapping(value = "/upload-excel", consumes = "multipart/form-data") public Mono<String> uploadExcel(@RequestPart("file") FilePart filePart) { // 后续处理文件内容 return processExcelFile(filePart) .then(Mono.just("文件处理完成")); } }
注意:必须用
@RequestPart注解,而不是@RequestParam,因为multipart/form-data类型的请求需要用@RequestPart来绑定文件部分。
2. 无本地保存的文件内容解析
直接通过FilePart.content()获取文件的Flux<DataBuffer>,将其转换为InputStream后用POI解析Excel内容。由于POI的操作是阻塞的,需要将解析逻辑放到专门的阻塞线程池中,避免阻塞Webflux的事件循环:
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.core.io.buffer.DataBufferUtils; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; private Mono<Void> processExcelFile(FilePart filePart) { return DataBufferUtils.join(filePart.content()) .map(dataBuffer -> { // 将DataBuffer转换为InputStream,自动释放资源 return dataBuffer.asInputStream(true); }) // 切换到阻塞线程池处理POI解析 .publishOn(Schedulers.boundedElastic()) .flatMap(inputStream -> { try (XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) { // 编写解析Excel内容并写入PostgreSQL的逻辑 // 示例:遍历工作表、行、单元格 var sheet = workbook.getSheetAt(0); sheet.forEach(row -> { row.forEach(cell -> { // 处理单元格数据 }); }); return Mono.empty(); } catch (Exception e) { return Mono.error(e); } }); }
3. 正确的curl测试命令
确保curl请求的Content-Type为multipart/form-data,并且参数名和Controller中@RequestPart指定的一致:
curl -X POST http://localhost:8080/upload-excel \ -H "Content-Type: multipart/form-data" \ -F "file=@/path/to/your/excel/file.xlsx"
额外注意事项
- 确保项目已引入
spring-boot-starter-webflux依赖,这是Webflux响应式栈的核心依赖。 - 处理xlsx文件需引入POI相关依赖:
poi和poi-ooxml。 - 写入PostgreSQL时,使用Spring Data R2DBC的响应式API,保证整个流程非阻塞,契合Webflux高吞吐量的设计目标。
内容的提问来源于stack exchange,提问作者spike
相关产品推荐
相关产品推荐

