Class MultipartHttpMessageConverter

java.lang.Object
org.springframework.http.converter.multipart.MultipartHttpMessageConverter
All Implemented Interfaces:
HttpMessageConverter<MultiValueMap<String,?>>, SmartHttpMessageConverter<MultiValueMap<String,?>>
Direct Known Subclasses:
AllEncompassingFormHttpMessageConverter

public class MultipartHttpMessageConverter extends Object implements SmartHttpMessageConverter<MultiValueMap<String,?>>
Implementation of 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 Details

  • Method Details

    • setSupportedMediaTypes

      public void setSupportedMediaTypes(List<MediaType> supportedMediaTypes)
      Set the list of MediaType objects supported by this converter.
      See Also:
    • addSupportedMediaTypes

      public void addSupportedMediaTypes(MediaType... supportedMediaTypes)
      Add MediaType objects to be supported by this converter.

      The supplied MediaType objects will be appended to the list of supported MediaType objects.

      Parameters:
      supportedMediaTypes - a var-args list of MediaType objects to add
      See Also:
    • getSupportedMediaTypes

      public List<MediaType> 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 via canWrite(clazz, null. The list may also exclude MIME types supported only for a specific class. Alternatively, use HttpMessageConverter.getSupportedMediaTypes(Class) for a more precise list.
      Specified by:
      getSupportedMediaTypes in interface HttpMessageConverter<MultiValueMap<String,?>>
      Returns:
      the list of supported media types
      See Also:
    • getPartConverters

      public List<HttpMessageConverter<?>> getPartConverters()
      Return the configured converters for MIME parts.
    • setCharset

      public void setCharset(@Nullable Charset charset)
      Set the default character set to use for reading and writing form data when the request or response Content-Type header 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) multipartCharset is also set, in which case part headers are encoded as ASCII and filename is encoded with the encoded-word syntax from RFC 2047.

      By default, this is set to "UTF-8".

    • setMultipartCharset

      public void setMultipartCharset(Charset charset)
      Set the character set to use when writing multipart data to encode file names. Encoding is based on the encoded-word syntax defined in RFC 2047 and relies on MimeUtility from jakarta.mail.

      As of 5.0 by default part headers, including Content-Disposition (and its filename parameter) will be encoded based on the setting of setCharset(Charset) or UTF-8 by 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:

      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 maxInMemorySize is 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

      public boolean canRead(ResolvableType elementType, @Nullable MediaType mediaType)
      Description copied from interface: SmartHttpMessageConverter
      Indicates whether the given type can be read by this converter. This method should perform the same checks as HttpMessageConverter.canRead(Class, MediaType) with additional ones related to the generic type.
      Specified by:
      canRead in interface SmartHttpMessageConverter<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 be null if not specified. Typically, the value of a Content-Type header.
      Returns:
      true if readable; false otherwise
    • read

      Description copied from interface: SmartHttpMessageConverter
      Read an object of the given type from the given input message, and returns it.
      Specified by:
      read in interface SmartHttpMessageConverter<MultiValueMap<String,?>>
      Parameters:
      type - the (potentially generic) type of object to return. This type must have previously been passed to the canRead method of this interface, which must have returned true. 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 from
      hints - additional information about how to encode
      Returns:
      the converted object
      Throws:
      IOException - in case of I/O errors
      HttpMessageNotReadableException - in case of conversion errors
    • canWrite

      public boolean canWrite(ResolvableType targetType, Class<?> valueClass, @Nullable MediaType mediaType)
      Description copied from interface: SmartHttpMessageConverter
      Indicates 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:
      canWrite in interface SmartHttpMessageConverter<MultiValueMap<String,?>>
      Parameters:
      targetType - the (potentially generic) target type to test for writability (can be ResolvableType.NONE if 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 writability
      mediaType - the media type to write (can be null if not specified); typically the value of an Accept header.
      Returns:
      true if writable; false otherwise
    • write

      public void write(MultiValueMap<String,?> map, ResolvableType type, @Nullable MediaType contentType, HttpOutputMessage outputMessage, @Nullable Map<String,Object> hints) throws IOException, HttpMessageNotWritableException
      Description copied from interface: SmartHttpMessageConverter
      Write a given object to the given output message.
      Specified by:
      write in interface SmartHttpMessageConverter<MultiValueMap<String,?>>
      Parameters:
      map - the object to write to the output message. The type of this object must have previously been passed to the canWrite method of this interface, which must have returned true.
      type - the (potentially generic) type of object to write. This type must have previously been passed to the canWrite method of this interface, which must have returned true. Can be ResolvableType.NONE if 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 be null to indicate that the default content type of the converter must be used. If not null, this media type must have previously been passed to the canWrite method of this interface, which must have returned true.
      outputMessage - the message to write to
      hints - additional information about how to encode
      Throws:
      IOException - in case of I/O errors
      HttpMessageNotWritableException - in case of conversion errors
    • getHttpEntity

      protected HttpEntity<?> getHttpEntity(Object part)
      Return an HttpEntity for the given part Object.
      Parameters:
      part - the part to return an HttpEntity for
      Returns:
      the part Object itself it is an HttpEntity, or a newly built HttpEntity wrapper for that part
    • getFilename

      protected @Nullable String getFilename(Object part)
      Return the filename of the given multipart part. This value will be used for the Content-Disposition header.

      The default implementation returns Resource.getFilename() if the part is a Resource, and null in other cases. Can be overridden in subclasses.

      Parameters:
      part - the part to determine the file name for
      Returns:
      the filename, or null if not known