简体   繁体   中英

Jersey Multipart Form Data Default Value?

I have a method that accepts type Multipart Form Data. One of the parameters to this method is a file form data param, shown by

@FormDataParam("file") InputStream inputStream,
@FormDataParam("file") FormDataContentDisposition contentDispositionHeader

I want to be able to hit this endpoint sometimes without providing the form data param file , but right now when I leave it out the method returns a 400 bad request immediately. Is there a way I can set it up so that I can leave it out? Or is there some way I can set a default value for this (ie to null?). Any help would be appreciated. My method declaration is below:

@POST
@Path("/publish")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response publish(@Auth Key key,
                        @QueryParam("email") String email,
                        @HeaderParam("password") String password,
                        @QueryParam("type") PublishType type,
                        @QueryParam("message") String message,
                        @FormDataParam("file") InputStream inputStream,
                        @FormDataParam("file") FormDataContentDisposition
                              contentDispositionHeader,
                        @FormDataParam("title") @DefaultValue("") String videoTitle) {
    // code here
}

In the end, I want to create an endpoint where a user can publish text to a database, and optionally include an image or some type of media. Let me know if there is another way I can achieve this.

Thank you!

It's not pretty, but the only thing I can think of (if you don't want to post any body), is to use Jersey's ContainerRequest that you can inject into the method. Then if there is any body, get the multipart as FormDataMultiPart and just traverse the parts manually.

@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String post(@Context ContainerRequest request) {
    final String contentLength = request.getHeaderString(HttpHeaders.CONTENT_LENGTH);
    if (contentLength != null && Integer.parseInt(contentLength) != 0) {
        FormDataMultiPart multiPart = request.readEntity(FormDataMultiPart.class);
        FormDataBodyPart part = multiPart.getField("test");
        String result = part.getValueAs(String.class);
        return result;
    }
    return "no body";
}

Below is a complete test

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.media.multipart.*;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import javax.ws.rs.*;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.util.logging.Logger;

import static org.junit.Assert.assertEquals;

/**
 * Example with default value for multipart field.
 *
 * Dependencies for JUnit test.
 *
 *   <dependency>
 *     <groupId>org.glassfish.jersey.test-framework.providers</groupId>
 *     <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
 *     <scope>test</scope>
 *     <version>${jersey2.version}</version>
 *   </dependency>
 *   <dependency>
 *     <groupId>org.glassfish.jersey.media</groupId>
 *     <artifactId>jersey-media-multipart</artifactId>
 *     <version>${jersey2.version}</version>
 *  </dependency>
 */
public class MultiPartMissingTest extends JerseyTest {

    @Path("test")
    public static class TestResource {

        @POST
        @Produces(MediaType.TEXT_PLAIN)
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        public String post(@Context ContainerRequest request) {
            final String contentLength = request.getHeaderString(HttpHeaders.CONTENT_LENGTH);
            if (contentLength != null && Integer.parseInt(contentLength) != 0) {
                FormDataMultiPart multiPart = request.readEntity(FormDataMultiPart.class);
                FormDataBodyPart part = multiPart.getField("test");
                String result = part.getValueAs(String.class);
                return result;
            }
            return "no body";
        }
    }


    @Override
    public ResourceConfig configure() {
        return new ResourceConfig()
                .register(TestResource.class)
                .register(MultiPartFeature.class)
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true))
                .register(new ExceptionMapper<Throwable>() {
                    @Override
                    public Response toResponse(Throwable t) {
                        t.printStackTrace();
                        return Response.serverError().entity(t.getMessage()).build();
                    }
                });
    }

    @Override
    public void configureClient(ClientConfig config) {
        config.register(MultiPartFeature.class);
    }

    @Test
    public void testWithBody() {
        final MultiPart multiPart = new FormDataMultiPart()
                .field("test", "testing");

        final Response response = target("test")
                .request()
                .post(Entity.entity(multiPart, multiPart.getMediaType()));

        assertEquals(200, response.getStatus());
        assertEquals("testing", response.readEntity(String.class));
    }

    @Test
    public void withoutBody() {
        final Response response = target("test")
                .request()
                .post(null);

        assertEquals(200, response.getStatus());
        assertEquals("no body", response.readEntity(String.class));
    }
}

You can simply state that the file param is not required. See below:

@POST
@Path("/publish")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response publish(
        @Multipart("key") Key key,
        @Multipart(value = "file", required = false) Attachment file) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM