Class MultipartHttpMessageConverter
- All Implemented Interfaces:
HttpMessageConverter<MultiValueMap<String,?>>, SmartHttpMessageConverter<MultiValueMap<String, ?>>
- Direct Known Subclasses:
AllEncompassingFormHttpMessageConverter
HttpMessageConverter to read and write
multipart data (for example, file uploads).
This converter can read "multipart/form-data"
and "multipart/mixed" messages as
MultiValueMap<String, Part>, and
write MultiValueMap<String, Object> as
multipart messages.
On Servlet containers, the reading of multipart messages should be
delegated to the MultipartResolver.
Multipart Data
By default, "multipart/form-data" is used as the content type when
writing multipart data. It is also possible to write
multipart data using other multipart subtypes such as "multipart/mixed"
and "multipart/related", as long as the multipart subtype is registered
as a supported media type and the
desired multipart subtype is specified as the content type when
writing the multipart data. Note that "multipart/mixed"
is registered as a supported media type by default.
When writing multipart data, this converter uses other
HttpMessageConverters to write the respective
MIME parts. By default, basic converters are registered for byte array,
String, and Resource. This can be set with the main
constructor.
Examples
The following snippet shows how to submit an HTML form using the
"multipart/form-data" content type.
RestClient restClient = RestClient.create();
// MultipartHttpMessageConverter is configured by default
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("field 1", "value 1");
form.add("field 2", "value 2");
form.add("field 2", "value 3");
form.add("field 3", 4);
ResponseEntity<Void> response = restClient.post()
.uri("https://example.com/myForm")
.contentType(MULTIPART_FORM_DATA)
.body(form)
.retrieve()
.toBodilessEntity();
The following snippet shows how to do a file upload using the
"multipart/form-data" content type.
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("field 1", "value 1");
parts.add("file", new ClassPathResource("myFile.jpg"));
ResponseEntity<Void> response = restClient.post()
.uri("https://example.com/myForm")
.contentType(MULTIPART_FORM_DATA)
.body(parts)
.retrieve()
.toBodilessEntity();
The following snippet shows how to decode a multipart response.
MultiValueMap<String, Part> body = this.restClient.get()
.uri("https://example.com/parts/42")
.accept(MediaType.MULTIPART_FORM_DATA)
.retrieve()
.body(new ParameterizedTypeReference<>() {});- Since:
- 7.1
- Author:
- Brian Clozel, Arjen Poutsma, Rossen Stoyanchev, Juergen Hoeller, Sam Brannen
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionCreate a new converter instance with default converter instances for reading and writing parts.MultipartHttpMessageConverter(Iterable<HttpMessageConverter<?>> converters) Create a new converter instance with the given converter instances for reading and writing parts. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddSupportedMediaTypes(MediaType... supportedMediaTypes) AddMediaTypeobjects to be supported by this converter.booleancanRead(ResolvableType elementType, @Nullable MediaType mediaType) Indicates whether the given type can be read by this converter.booleancanWrite(ResolvableType targetType, Class<?> valueClass, @Nullable MediaType mediaType) Indicates whether the given class can be written by this converter.getFilename(Object part) Return the filename of the given multipart part.protected HttpEntity<?> getHttpEntity(Object part) Return anHttpEntityfor the given part Object.Return the configured converters for MIME parts.Return the list of media types supported by this converter.read(ResolvableType type, HttpInputMessage message, @Nullable Map<String, Object> hints) Read an object of the given type from the given input message, and returns it.voidsetCharset(@Nullable Charset charset) Set the default character set to use for reading and writing form data when the request or responseContent-Typeheader does not explicitly specify it.voidsetMaxDiskUsagePerPart(long maxDiskUsagePerPart) Configure the maximum amount of disk space allowed for file parts.voidsetMaxHeadersSize(int byteCount) Configure the maximum amount of memory that is allowed per headers section of each part.voidsetMaxInMemorySize(int maxInMemorySize) Configure the maximum amount of memory allowed per part.voidsetMaxParts(int maxParts) Specify the maximum number of parts allowed in a given multipart request.voidsetMultipartCharset(Charset charset) Set the character set to use when writing multipart data to encode file names.voidsetSupportedMediaTypes(List<MediaType> supportedMediaTypes) Set the list ofMediaTypeobjects supported by this converter.voidwrite(MultiValueMap<String, ?> map, ResolvableType type, @Nullable MediaType contentType, HttpOutputMessage outputMessage, @Nullable Map<String, Object> hints) Write a given object to the given output message.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface HttpMessageConverter
canWriteRepeatedly, getSupportedMediaTypesMethods inherited from interface SmartHttpMessageConverter
canRead, canWrite, read, write
-
Constructor Details
-
MultipartHttpMessageConverter
Create a new converter instance with the given converter instances for reading and writing parts.- Parameters:
converters- the converters to use for reading and writing parts
-
MultipartHttpMessageConverter
public MultipartHttpMessageConverter()Create a new converter instance with default converter instances for reading and writing parts.- See Also:
-
-
Method Details
-
setSupportedMediaTypes
-
addSupportedMediaTypes
AddMediaTypeobjects to be supported by this converter.The supplied
MediaTypeobjects will be appended to the list of supported MediaType objects.- Parameters:
supportedMediaTypes- a var-args list ofMediaTypeobjects to add- See Also:
-
getSupportedMediaTypes
Return the list of media types supported by this converter. The list may not apply to every possible target element type and calls to this method should typically be guarded viacanWrite(clazz, null. The list may also exclude MIME types supported only for a specific class. Alternatively, useHttpMessageConverter.getSupportedMediaTypes(Class)for a more precise list.- Specified by:
getSupportedMediaTypesin interfaceHttpMessageConverter<MultiValueMap<String,?>> - Returns:
- the list of supported media types
- See Also:
-
getPartConverters
Return the configured converters for MIME parts. -
setCharset
Set the default character set to use for reading and writing form data when the request or responseContent-Typeheader does not explicitly specify it.As of 4.3, this is also used as the default charset for the conversion of text bodies in a multipart request.
As of 5.0, this is also used for part headers including
Content-Disposition(and its filename parameter) unless (the mutually exclusive)multipartCharsetis also set, in which case part headers are encoded as ASCII and filename is encoded with theencoded-wordsyntax from RFC 2047.By default, this is set to "UTF-8".
-
setMultipartCharset
Set the character set to use when writing multipart data to encode file names. Encoding is based on theencoded-wordsyntax defined in RFC 2047 and relies onMimeUtilityfromjakarta.mail.As of 5.0 by default part headers, including
Content-Disposition(and its filename parameter) will be encoded based on the setting ofsetCharset(Charset)orUTF-8by default.- See Also:
-
setMaxHeadersSize
public void setMaxHeadersSize(int byteCount) Configure the maximum amount of memory that is allowed per headers section of each part.By default, this is set to 10K.
- Parameters:
byteCount- the maximum amount of memory for headers
-
setMaxInMemorySize
public void setMaxInMemorySize(int maxInMemorySize) Configure the maximum amount of memory allowed per part. When the limit is exceeded:- File parts are written to a temporary file.
- Non-file parts are rejected with
DataBufferLimitException.
By default, this is set to 256K.
- Parameters:
maxInMemorySize- the in-memory limit in bytes; if set to -1 the entire contents will be stored in memory
-
setMaxDiskUsagePerPart
public void setMaxDiskUsagePerPart(long maxDiskUsagePerPart) Configure the maximum amount of disk space allowed for file parts.By default, this is set to -1, meaning that there is no maximum.
Note that this property is ignored when
maxInMemorySizeis set to -1. -
setMaxParts
public void setMaxParts(int maxParts) Specify the maximum number of parts allowed in a given multipart request.By default, this is set to -1, meaning that there is no maximum.
-
canRead
Description copied from interface:SmartHttpMessageConverterIndicates whether the given type can be read by this converter. This method should perform the same checks asHttpMessageConverter.canRead(Class, MediaType)with additional ones related to the generic type.- Specified by:
canReadin interfaceSmartHttpMessageConverter<MultiValueMap<String,?>> - Parameters:
elementType- the (potentially generic) type to test for readability. The type source may be used for retrieving additional information (the related method signature for example) when relevant.mediaType- the media type to read, can benullif not specified. Typically, the value of aContent-Typeheader.- Returns:
trueif readable;falseotherwise
-
read
public MultiValueMap<String,Part> read(ResolvableType type, HttpInputMessage message, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotReadableExceptionDescription copied from interface:SmartHttpMessageConverterRead an object of the given type from the given input message, and returns it.- Specified by:
readin interfaceSmartHttpMessageConverter<MultiValueMap<String,?>> - Parameters:
type- the (potentially generic) type of object to return. This type must have previously been passed to thecanReadmethod of this interface, which must have returnedtrue. The type source may be used for retrieving additional information (the related method signature for example) when relevant.message- the HTTP input message to read fromhints- additional information about how to encode- Returns:
- the converted object
- Throws:
IOException- in case of I/O errorsHttpMessageNotReadableException- in case of conversion errors
-
canWrite
public boolean canWrite(ResolvableType targetType, Class<?> valueClass, @Nullable MediaType mediaType) Description copied from interface:SmartHttpMessageConverterIndicates whether the given class can be written by this converter.This method should perform the same checks as
HttpMessageConverter.canWrite(Class, MediaType)with additional ones related to the generic type.- Specified by:
canWritein interfaceSmartHttpMessageConverter<MultiValueMap<String,?>> - Parameters:
targetType- the (potentially generic) target type to test for writability (can beResolvableType.NONEif not specified). The type source may be used for retrieving additional information (the related method signature for example) when relevant.valueClass- the source object class to test for writabilitymediaType- the media type to write (can benullif not specified); typically the value of anAcceptheader.- Returns:
trueif writable;falseotherwise
-
write
public void write(MultiValueMap<String, ?> map, ResolvableType type, @Nullable MediaType contentType, HttpOutputMessage outputMessage, @Nullable Map<String, throws IOException, HttpMessageNotWritableExceptionObject> hints) Description copied from interface:SmartHttpMessageConverterWrite a given object to the given output message.- Specified by:
writein interfaceSmartHttpMessageConverter<MultiValueMap<String,?>> - Parameters:
map- the object to write to the output message. The type of this object must have previously been passed to thecanWritemethod of this interface, which must have returnedtrue.type- the (potentially generic) type of object to write. This type must have previously been passed to thecanWritemethod of this interface, which must have returnedtrue. Can beResolvableType.NONEif not specified. The type source may be used for retrieving additional information (the related method signature for example) when relevant.contentType- the content type to use when writing. May benullto indicate that the default content type of the converter must be used. If notnull, this media type must have previously been passed to thecanWritemethod of this interface, which must have returnedtrue.outputMessage- the message to write tohints- additional information about how to encode- Throws:
IOException- in case of I/O errorsHttpMessageNotWritableException- in case of conversion errors
-
getHttpEntity
Return anHttpEntityfor the given part Object.- Parameters:
part- the part to return anHttpEntityfor- Returns:
- the part Object itself it is an
HttpEntity, or a newly builtHttpEntitywrapper for that part
-
getFilename
Return the filename of the given multipart part. This value will be used for theContent-Dispositionheader.The default implementation returns
Resource.getFilename()if the part is aResource, andnullin other cases. Can be overridden in subclasses.- Parameters:
part- the part to determine the file name for- Returns:
- the filename, or
nullif not known
-