Returning both image and JSON in multipart respons

2019-08-14 16:38发布

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.

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-14 16:48

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 the org.glassfish.jersey.media.multipart package.

To use multipart features you need to add jersey-media-multipart module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.22.2</version>
</dependency>

And don't forget registering the MultiPartFeature:

final Application application = new ResourceConfig()
    .packages("org.glassfish.jersey.examples.multipart")
    .register(MultiPartFeature.class)

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 the com.sun.jersey.multipart package.

The jersey-multipart dependecy is necessary:

<dependency>
    <groupId>com.sun.jersey.contribs</groupId>
    <artifactId>jersey-multipart</artifactId>
    <version>1.19.1</version>
</dependency>
查看更多
登录 后发表回答