I'm learning Jersey by trying to create a Rest service that receives an image from client, processes the image and returns a new image with additional information (i.e., about processing details).
So far, the uploading works fine. I'm now concerned with creating the response. I'm thinking of creating a multipart response that contains the new image in 1 bodypart while adding a JSON string (that contains the additional info) into another body part. However I wasn't successful. The code is as follows:
File image = process(oldImage);
Info info = getInfo();
String jsonStr = toJson(info);
MimeMultipart multiPart = new MimeMultipart();
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setContent(Files.readAllBytes(image.toPath()), MediaType.APPLICATION_OCTET_STREAM);
MimeBodyPart jsonPart = new MimeBodyPart();
jsonPart.setContent(jsonStr, MediaType.APPLICATION_JSON);
multiPart.addBodyPart(imagePart);
multiPart.addBodyPart(jsonPart);
return Response.ok(multiPart, "multipart/mixed").build();
I received an error message as follows:
MessageBodyWriter not found for media type=multipart/mixed, type=class com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeMultipart, genericType=class com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeMultipart.
I've been searching for a while however haven't found anyway to fix it. It would be great of you can help pointing out what's wrong with the code and what should be a good approach to take regarding this issue.
I think
com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeMultipart
is not the class you want.Jersey 2.x
For Jersey 2.x, use the
MultiPart
class from theorg.glassfish.jersey.media.multipart
package.To use multipart features you need to add
jersey-media-multipart
module to yourpom.xml
file:And don't forget registering the
MultiPartFeature
:There's an example of multipart request on Jersey GitHub repository.
For more details, have a look at Jersey 2.x documentation.
Jersey 1.x
For the old Jersey 1.x, you can use the
MultiPart
class from thecom.sun.jersey.multipart
package.The
jersey-multipart
dependecy is necessary: