Skip to content

Multipart form data

Rafat J. Al-Barouki edited this page Apr 25, 2021 · 1 revision

Multipart form data

For defining a multipart form data, the content type of the request should be multipart/form-data. Once domino-rest finds out that this request is a multipart form data request, it will try to search for javax.ws.rs.FormData fields which indicates the parts of the request.

For example:

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Consumes;

@RequestFactory
public interface MultipartService {

  @POST
  @Path("upload")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  void textMultipart(@FormParam("id") String id, @FormParam("file") byte[] fileContent);
}

This will generate a request with two parts, one contains the id and the other contains the binary content of the file with a name file.

Sending JSONs

When sending objects that has ObjectMapper, domino-rest uses domino-jackson to serialize the object and get the json value to send it in the request. Same goes when defining a javax.ws.rs.FormData that has a serializable object as follows:

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Consumes;

@RequestFactory
public interface MultipartService {

  @POST
  @Path("test")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  void objectMultipart(
      @FormParam("sampleObjectJson") SampleObject sampleObject,
      @FormParam("file") byte[] fileContent);
}

The SampleObject will be sent as a json inside the part sampleObjectJson

Multipart context

Sometimes, multipart form data request has a lot of parts, these parts can be grouped using @Multipart as follows:

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Consumes;

@RequestFactory
public interface MultipartService {

  @POST
  @Path("test")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  void wrapperMultipart(@Multipart SampleMultipartRequest request);
}

And this is the SampleMultipartRequest:

import javax.ws.rs.FormParam;

public class SampleMultipartRequest {

  @FormParam("sampleObjectJson")
  private SampleObject sampleObject;

  @FormParam("file")
  private byte[] fileContent;

  @FormParam("size")
  private int size;

  public SampleObject getSampleObject() {
    return sampleObject;
  }

  public void setSampleObject(SampleObject sampleObject) {
    this.sampleObject = sampleObject;
  }

  public byte[] getFileContent() {
    return fileContent;
  }

  public void setFileContent(byte[] fileContent) {
    this.fileContent = fileContent;
  }

  public int getSize() {
    return size;
  }

  public void setSize(int size) {
    this.size = size;
  }
}