Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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}.
*
* <p>In default, non-streaming mode, this message reader stores the
* {@linkplain Part#content() contents} of parts smaller than
Expand All @@ -42,7 +41,7 @@
* {@link #setFileStorageDirectory(Path) fileStorageDirectory}.
*
* <p>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
Expand Down Expand Up @@ -162,13 +161,12 @@ public void setHeadersCharset(Charset headersCharset) {

@Override
public List<MediaType> 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
Expand All @@ -187,6 +185,9 @@ public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage mess
}
Flux<MultipartParser.Token> 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
Expand All @@ -203,7 +204,7 @@ public Flux<Part> 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());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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}.
Expand All @@ -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.
* <p>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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ final class PartGenerator extends BaseSubscriber<MultipartParser.Token> {

private final MonoSink<Part> sink;

private final boolean requireFormFieldName;

private final int maxInMemorySize;

private final long maxDiskUsagePerPart;
Expand All @@ -68,10 +70,11 @@ final class PartGenerator extends BaseSubscriber<MultipartParser.Token> {
private final Scheduler blockingOperationScheduler;


private PartGenerator(MonoSink<Part> sink, int maxInMemorySize, long maxDiskUsagePerPart,
Mono<Path> fileStorageDirectory, Scheduler blockingOperationScheduler) {
private PartGenerator(MonoSink<Part> sink, boolean requireFormFieldName, int maxInMemorySize,
long maxDiskUsagePerPart, Mono<Path> fileStorageDirectory, Scheduler blockingOperationScheduler) {

this.sink = sink;
this.requireFormFieldName = requireFormFieldName;
this.maxInMemorySize = maxInMemorySize;
this.maxDiskUsagePerPart = maxDiskUsagePerPart;
this.fileStorageDirectory = fileStorageDirectory;
Expand All @@ -81,12 +84,13 @@ private PartGenerator(MonoSink<Part> sink, int maxInMemorySize, long maxDiskUsag
/**
* Creates parts from a given stream of tokens.
*/
public static Mono<Part> createPart(Flux<MultipartParser.Token> tokens, int maxInMemorySize,
long maxDiskUsagePerPart, Mono<Path> fileStorageDirectory, Scheduler blockingOperationScheduler) {
public static Mono<Part> createPart(Flux<MultipartParser.Token> tokens, boolean requireFormFieldName,
int maxInMemorySize, long maxDiskUsagePerPart, Mono<Path> 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());
Expand Down Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -22,13 +23,15 @@
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;
import reactor.core.publisher.Flux;
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;
Expand Down Expand Up @@ -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: <root>\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<Part> 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("<root>");
byte[] bytes = new ByteArrayDecoder().decodeToMono(first.content(), forClass(byte[].class),
null, emptyMap()).block();
assertThat(bytes).isEqualTo(text);
testBrowserFormField(parts.get(1), "label", "hello");
}

@ParameterizedDefaultPartHttpMessageReaderTest
Expand Down