7.1.3 Multipart Client Uploads

The Micronaut HTTP Client supports the ability to create multipart requests. In order to build a multipart request you must set the content type to multipart/form-data and set the body to be an instance of MultipartBody:

For example:

Creating the body

  1. import io.micronaut.http.client.multipart.MultipartBody;
  2. String toWrite = "test file";
  3. File file = File.createTempFile("data", ".txt");
  4. FileWriter writer = new FileWriter(file);
  5. writer.write(toWrite);
  6. writer.close();
  7. MultipartBody requestBody = MultipartBody.builder() (1)
  8. .addPart( (2)
  9. "data",
  10. file.getName(),
  11. MediaType.TEXT_PLAIN_TYPE,
  12. file
  13. ).build() ; (3)

Creating the body

  1. import io.micronaut.http.multipart.CompletedFileUpload
  2. import io.micronaut.http.multipart.StreamingFileUpload
  3. import io.micronaut.http.client.multipart.MultipartBody
  4. import org.reactivestreams.Publisher
  5. File file = new File(uploadDir, "data.txt")
  6. file.text = "test file"
  7. file.createNewFile()
  8. MultipartBody requestBody = MultipartBody.builder() (1)
  9. .addPart( (2)
  10. "data",
  11. file.name,
  12. MediaType.TEXT_PLAIN_TYPE,
  13. file
  14. ).build() (3)

Creating the body

  1. import io.micronaut.http.client.multipart.MultipartBody
  2. val toWrite = "test file"
  3. val file = File.createTempFile("data", ".txt")
  4. val writer = FileWriter(file)
  5. writer.write(toWrite)
  6. writer.close()
  7. val requestBody = MultipartBody.builder() (1)
  8. .addPart( (2)
  9. "data",
  10. file.name,
  11. MediaType.TEXT_PLAIN_TYPE,
  12. file
  13. ).build() (3)
1You need to create a MultipartBody builder for adding parts to the body.
2Method to add a part to the body, in this case a file. There are different variations of this method which you can see in MultipartBody.Builder.
3Call the build method to assemble all parts from the builder into a MultipartBody. At least one part is required.

Creating a request

  1. HttpRequest.POST("/multipart/upload", requestBody) (1)
  2. .contentType(MediaType.MULTIPART_FORM_DATA_TYPE) (2)

Creating a request

  1. HttpRequest.POST("/multipart/upload", requestBody) (1)
  2. .contentType(MediaType.MULTIPART_FORM_DATA_TYPE) (2)

Creating a request

  1. HttpRequest.POST("/multipart/upload", requestBody) (1)
  2. .contentType(MediaType.MULTIPART_FORM_DATA_TYPE) (2)
1The multipart request body with different sets of data.
2Set the content-type header of the request to multipart/form-data.