在前端,我们有一个表单,它将数据作为多部分/表单数据发送,我们需要在控制器中接收数据,同一属性可能有几条记录
Content-Disposition: form-data; name="ids"
30
-----------------------------313589022531437741264012237550
Content-Disposition: form-data; name="ids"
225
-----------------------------313589022531437741264012237550
Content-Disposition: form-data; name="ids"
226
-----------------------------313589022531437741264012237550
Content-Disposition: form-data; name="ids"
如何在控制器中接收这些值?
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Mono<String> create(@RequestPart("ids") List<Long> ids) {
// ...
}
List<Long>
和Long[]
无法正常工作。
所述请求
MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
bodyBuilder.part("ids", 22);
bodyBuilder.part("ids", 33);
webTestClient.post()
.uri("/create")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(bodyBuilder.build()))
.exchange()
.expectStatus().isOk();
错误
org.springframework.web.server.ServerWebInputException: 400 BAD_REQUEST "Failed to read HTTP message"; nested exception is org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize value of type `java.util.ArrayList<java.lang.Integer>` from Integer value (token `JsonToken.VALUE_NUMBER_INT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<java.lang.Integer>` from Integer value (token `JsonToken.VALUE_NUMBER_INT`)
at [Source: (org.springframework.core.io.buffer.DefaultDataBuffer$DefaultDataBufferInputStream); line: 1, column: 1]
at org.springframework.web.reactive.result.method.annotation.AbstractMessageReaderArgumentResolver.handleReadError(AbstractMessageReaderArgumentResolver.java:224)
at org.springframework.web.reactive.result.method.annotation.AbstractMessageReaderArgumentResolver.lambda$readBody$3(AbstractMessageReaderArgumentResolver.java:190)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94)
下面的回购协议演示了这个问题:
https://github.com/alxxyz/spring-request-part-demo
2条答案
按热度按时间bxgwgixi1#
如果您将ID形成为数组,则会正确处理它们:
vatpfxk52#
试试看: