Skip to main content

Reading Attachments

Individual parts can be mapped to StreamSource, InputStream, DataSource or custom Java types for which message body readers are available.

For example:

@POST
@Path("/books/jaxbjson")
@Produces("text/xml")
public Response addBookJaxbJson(
   @Multipart(value = "rootPart", type = "text/xml") Book2 b1,
   @Multipart(value = "book2", type = "application/json") Book b2) 
   throws Exception {
}

Note that in this example it is expected that the root part named 'rootPart' is a text-xml Book representation, while a part named 'book2' is a Book JSON sequence.

All attachment parts can be accessed as a list of CXF JAX-RS Attachment objects with every Attachment instance providing all the information about a specific part. Similarly, the whole request body can be represented as a CXF JAX-RS MultipartBody:

@POST
public void addAttachments(MultipartBody body) throws Exception {
List<Attachment> all = body.getAllAtachments();
Attachment att = body.getRootAttachment();
}

When handling complex multipart/form-data submissions (such as those containing files) MultipartBody (and Attachment) need to be used directly.

When working with either List of Attachments or MultipartBody, one may want to process the individual parts with the help of some custom procedures. It is also possible to do the following:

@POST
public void addAttachments(MultipartBody body) throws Exception {
   Book book = body.getAttachmentObject("bookPart", Book.class);
}

@POST
public void addAttachments(List<Attachment> attachments) 
   throws Exception {
   for (Attachment attachment : attachments) {
      Book book = attachment.getObject(Book.class);
   }  
}

When reading large attachments, the "attachment-directory" and "attachment-memory-threshold" contextual properties can be used to control what folder the attachments exceeding a given threshold (in bytes) can be temporarily saved to.

Did this page help you?

If you find any issues with this page or its content – a typo, a missing step, or a technical error – let us know how we can improve!