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
import io.micronaut.http.client.multipart.MultipartBody;
String toWrite = "test file";
File file = File.createTempFile("data", ".txt");
FileWriter writer = new FileWriter(file);
writer.write(toWrite);
writer.close();
MultipartBody requestBody = MultipartBody.builder() (1)
.addPart( (2)
"data",
file.getName(),
MediaType.TEXT_PLAIN_TYPE,
file
).build() ; (3)
Creating the body
import io.micronaut.http.multipart.CompletedFileUpload
import io.micronaut.http.multipart.StreamingFileUpload
import io.micronaut.http.client.multipart.MultipartBody
import org.reactivestreams.Publisher
File file = new File(uploadDir, "data.txt")
file.text = "test file"
file.createNewFile()
MultipartBody requestBody = MultipartBody.builder() (1)
.addPart( (2)
"data",
file.name,
MediaType.TEXT_PLAIN_TYPE,
file
).build() (3)
Creating the body
import io.micronaut.http.client.multipart.MultipartBody
val toWrite = "test file"
val file = File.createTempFile("data", ".txt")
val writer = FileWriter(file)
writer.write(toWrite)
writer.close()
val requestBody = MultipartBody.builder() (1)
.addPart( (2)
"data",
file.name,
MediaType.TEXT_PLAIN_TYPE,
file
).build() (3)
1 | You need to create a MultipartBody builder for adding parts to the body. |
2 | Method 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. |
3 | Call the build method to assemble all parts from the builder into a MultipartBody. At least one part is required. |
Creating a request
HttpRequest.POST("/multipart/upload", requestBody) (1)
.contentType(MediaType.MULTIPART_FORM_DATA_TYPE) (2)
Creating a request
HttpRequest.POST("/multipart/upload", requestBody) (1)
.contentType(MediaType.MULTIPART_FORM_DATA_TYPE) (2)
Creating a request
HttpRequest.POST("/multipart/upload", requestBody) (1)
.contentType(MediaType.MULTIPART_FORM_DATA_TYPE) (2)
1 | The multipart request body with different sets of data. |
2 | Set the content-type header of the request to multipart/form-data . |