From a073198fef14b3179d8a6c0c1c0092960f5ba4d1 Mon Sep 17 00:00:00 2001 From: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:35:14 -0800 Subject: [PATCH] Read mixed and related multipart bodies as parts WebClient rejects multipart/mixed and multipart/related when reading a Flux of parts. Reading into a map instead requires a name for each part, which these media types do not require. Use the same media types for both readers. Keep an unnamed part's original bytes so a text part retains its byte order when read back. See gh-30230 Signed-off-by: Kayokoi <113896798+wozhenbang2004@users.noreply.github.com> --- .../DefaultPartHttpMessageReader.java | 17 ++++++----- .../multipart/MultipartHttpMessageReader.java | 2 +- .../http/codec/multipart/Part.java | 7 +++-- .../http/codec/multipart/PartGenerator.java | 19 +++++++----- .../DefaultPartHttpMessageReaderTests.java | 30 +++++++++++++++++++ 5 files changed, 57 insertions(+), 18 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java index 359d443d4d31..6809629ccb41 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReader.java @@ -9,7 +9,6 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @@ -32,8 +31,8 @@ import org.springframework.util.unit.DataSize; /** - * Default {@code HttpMessageReader} for parsing {@code "multipart/form-data"} - * requests to a stream of {@link Part}s. + * Read a {@code multipart/form-data}, {@code multipart/mixed}, or + * {@code multipart/related} message as a stream of {@link Part parts}. * *

In default, non-streaming mode, this message reader stores the * {@linkplain Part#content() contents} of parts smaller than @@ -42,7 +41,7 @@ * {@link #setFileStorageDirectory(Path) fileStorageDirectory}. * *

This reader can be provided to {@link MultipartHttpMessageReader} in order - * to aggregate all parts into a Map. + * to aggregate named parts into a Map. * * @author Arjen Poutsma * @since 5.3 @@ -162,13 +161,12 @@ public void setHeadersCharset(Charset headersCharset) { @Override public List getReadableMediaTypes() { - return Collections.singletonList(MediaType.MULTIPART_FORM_DATA); + return MultipartHttpMessageReader.MIME_TYPES; } @Override public boolean canRead(ResolvableType elementType, @Nullable MediaType mediaType) { - return Part.class.equals(elementType.toClass()) && - (mediaType == null || MediaType.MULTIPART_FORM_DATA.isCompatibleWith(mediaType)); + return Part.class.equals(elementType.toClass()) && MultipartHttpMessageReader.supportsMediaType(mediaType); } @Override @@ -187,6 +185,9 @@ public Flux read(ResolvableType elementType, ReactiveHttpInputMessage mess } Flux allPartsTokens = MultipartParser.parse(message.getBody(), boundary, this.maxHeadersSize, this.headersCharset); + MediaType contentType = message.getHeaders().getContentType(); + boolean requireFormFieldName = MediaType.MULTIPART_MIXED.equalsTypeAndSubtype(contentType) || + MediaType.MULTIPART_RELATED.equalsTypeAndSubtype(contentType); AtomicInteger partCount = new AtomicInteger(); return allPartsTokens @@ -203,7 +204,7 @@ public Flux read(ResolvableType elementType, ReactiveHttpInputMessage mess this.maxParts + " allowed)"))); } else { - return PartGenerator.createPart(partsTokens, + return PartGenerator.createPart(partsTokens, requireFormFieldName, this.maxInMemorySize, this.maxDiskUsagePerPart, this.fileStorage.directory(), getBlockingOperationScheduler()); } diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageReader.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageReader.java index 48c82fa2c6fb..8eb33e1c173c 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageReader.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageReader.java @@ -75,7 +75,7 @@ public boolean canRead(ResolvableType elementType, @Nullable MediaType mediaType return supportsMediaType(mediaType) && MULTIPART_VALUE_TYPE.isAssignableFrom(elementType); } - private boolean supportsMediaType(@Nullable MediaType mediaType) { + static boolean supportsMediaType(@Nullable MediaType mediaType) { if (mediaType == null) { return true; } diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/Part.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/Part.java index ab985497ccfa..440968242454 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/Part.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/Part.java @@ -12,7 +12,7 @@ import org.springframework.http.HttpHeaders; /** - * Representation for a part in a "multipart/form-data" request. + * Representation of a part in a multipart HTTP message. * *

The origin of a multipart request may be a browser form in which case each * part is either a {@link FormFieldPart} or a {@link FilePart}. @@ -30,8 +30,11 @@ public interface Part { /** - * Return the name of the part in the multipart form. + * Return the name of the part from its {@code Content-Disposition} header. + *

For parts that may have no name, use + * {@code headers().getContentDisposition().getName()}. * @return the name of the part, never {@code null} or empty + * @throws IllegalStateException if the part has no name */ String name(); diff --git a/spring-web/src/main/java/org/springframework/http/codec/multipart/PartGenerator.java b/spring-web/src/main/java/org/springframework/http/codec/multipart/PartGenerator.java index bd3c18cf8ee4..e3ce73c35849 100644 --- a/spring-web/src/main/java/org/springframework/http/codec/multipart/PartGenerator.java +++ b/spring-web/src/main/java/org/springframework/http/codec/multipart/PartGenerator.java @@ -59,6 +59,8 @@ final class PartGenerator extends BaseSubscriber { private final MonoSink sink; + private final boolean requireFormFieldName; + private final int maxInMemorySize; private final long maxDiskUsagePerPart; @@ -68,10 +70,11 @@ final class PartGenerator extends BaseSubscriber { private final Scheduler blockingOperationScheduler; - private PartGenerator(MonoSink sink, int maxInMemorySize, long maxDiskUsagePerPart, - Mono fileStorageDirectory, Scheduler blockingOperationScheduler) { + private PartGenerator(MonoSink sink, boolean requireFormFieldName, int maxInMemorySize, + long maxDiskUsagePerPart, Mono fileStorageDirectory, Scheduler blockingOperationScheduler) { this.sink = sink; + this.requireFormFieldName = requireFormFieldName; this.maxInMemorySize = maxInMemorySize; this.maxDiskUsagePerPart = maxDiskUsagePerPart; this.fileStorageDirectory = fileStorageDirectory; @@ -81,12 +84,13 @@ private PartGenerator(MonoSink sink, int maxInMemorySize, long maxDiskUsag /** * Creates parts from a given stream of tokens. */ - public static Mono createPart(Flux tokens, int maxInMemorySize, - long maxDiskUsagePerPart, Mono fileStorageDirectory, Scheduler blockingOperationScheduler) { + public static Mono createPart(Flux tokens, boolean requireFormFieldName, + int maxInMemorySize, long maxDiskUsagePerPart, Mono fileStorageDirectory, + Scheduler blockingOperationScheduler) { return Mono.create(sink -> { - PartGenerator generator = new PartGenerator(sink, maxInMemorySize, maxDiskUsagePerPart, - fileStorageDirectory, blockingOperationScheduler); + PartGenerator generator = new PartGenerator(sink, requireFormFieldName, maxInMemorySize, + maxDiskUsagePerPart, fileStorageDirectory, blockingOperationScheduler); sink.onCancel(generator); sink.onRequest(l -> generator.requestToken()); @@ -118,7 +122,8 @@ protected void hookOnNext(MultipartParser.Token token) { } private void newPart(State currentState, HttpHeaders headers) { - if (MultipartUtils.isFormField(headers)) { + if (MultipartUtils.isFormField(headers) && + (!this.requireFormFieldName || headers.getContentDisposition().getName() != null)) { changeState(currentState, new FormFieldState(headers)); requestToken(); } diff --git a/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReaderTests.java b/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReaderTests.java index b653686c8402..6a7d5873e617 100644 --- a/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReaderTests.java +++ b/spring-web/src/test/java/org/springframework/http/codec/multipart/DefaultPartHttpMessageReaderTests.java @@ -13,6 +13,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; @@ -22,6 +23,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Subscription; import reactor.core.Exceptions; import reactor.core.publisher.BaseSubscriber; @@ -29,6 +31,7 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import org.springframework.core.codec.ByteArrayDecoder; import org.springframework.core.codec.DecodingException; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -66,6 +69,33 @@ class DefaultPartHttpMessageReaderTests extends AbstractLeakCheckingTests { @ParameterizedDefaultPartHttpMessageReaderTest void canRead(DefaultPartHttpMessageReader reader) { assertThat(reader.canRead(forClass(Part.class), MediaType.MULTIPART_FORM_DATA)).isTrue(); + assertThat(reader.canRead(forClass(Part.class), MediaType.MULTIPART_MIXED)).isTrue(); + assertThat(reader.canRead(forClass(Part.class), MediaType.MULTIPART_RELATED)).isTrue(); + assertThat(reader.canRead(forClass(Part.class), new MediaType("multipart", "alternative"))).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"mixed", "related"}) + void readUnnamedPart(String subtype) { + MediaType contentType = new MediaType("multipart", subtype, singletonMap("boundary", "batch")); + byte[] text = {(byte) 0xff, (byte) 0xfe, 'A', 0}; // UTF-16 with a little-endian BOM + DataBuffer body = this.bufferFactory.allocateBuffer(256) + .write("--batch\r\nContent-ID: \r\nContent-Type: text/plain; charset=UTF-16\r\n\r\n", UTF_8) + .write(text) + .write("\r\n--batch\r\nContent-Disposition: form-data; name=\"label\"\r\n\r\n", UTF_8) + .write("hello\r\n--batch--\r\n", UTF_8); + MockServerHttpRequest request = MockServerHttpRequest.post("/") + .contentType(contentType).body(Flux.just(body)); + DefaultPartHttpMessageReader reader = new DefaultPartHttpMessageReader(); + + List parts = reader.read(forClass(Part.class), request, emptyMap()).collectList().block(); + assertThat(parts).hasSize(2); + Part first = parts.get(0); + assertThat(first.headers().getFirst("Content-ID")).isEqualTo(""); + byte[] bytes = new ByteArrayDecoder().decodeToMono(first.content(), forClass(byte[].class), + null, emptyMap()).block(); + assertThat(bytes).isEqualTo(text); + testBrowserFormField(parts.get(1), "label", "hello"); } @ParameterizedDefaultPartHttpMessageReaderTest