Spring 当文件名丢失时,启动无法识别多部分表单数据元素

Spring Boot doesn't recognize multipart form-data element when filename is missing

我有这个代码:

@PostMapping("foobar")
public ResponseEntity<SaveLogsResult> foobar(@RequestPart("file") MultipartFile log, @RequestPart("env") MultipartFile json){
    return ResponseEntity.ok(fooService.saveFooBar(log, json, UUID.randomUUID().toString()));
}

两个应用程序向此端点发送正式正确的数据,一个严重失败并收到 HTTP 状态 400。

我设置了 logging.level.org.springframework.web=DEBUG 并且可以看到(在其他行中)这个:

Required request part 'env' is not present
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'env' is not present]
Completed 400 BAD_REQUEST

为了进一步诊断这个问题,我比较了一个工作(左)和一个非工作(右)请求。唯一不同的是 filename:

据我了解 RFC for Content-Disposition 省略 filename 是完全有效的:

Is followed by a string containing the original name of the file transmitted. The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. This parameter provides mostly indicative information. When used in combination with Content-Disposition: attachment, it is used as the default filename for an eventual "Save As" dialog presented to the user.

这是 Spring 中的错误吗?我使用 Spring Boot 2.6.2 不幸的是,我无法更改非工作组件以进行快速测试,因为它是一个购买的组件,不会经常收到错误修复。 我认为我的问题与描述的不同,因为故障只发生在特定场景下。

看来您必须提供文件名。看到这个 issue

This [The situation in which filename is not present] can lead to inconsistencies, e.g. you would get it with MultipartFile but not with collection or array of MultipartFile, and one can make the opposite argument that it should be rejected.

Why does it matter to have it injected as MultipartFile if it doesn't even have a filename? You could also inject it as InputStream or any other type supported by a registered HttpMessageConverter.