简体   繁体   English

Jersey 多部分表单数据默认值?

[英]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此方法的参数之一是file表单数据参数,如下所示

@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.我有时希望能够在不提供表单数据参数file的情况下访问此端点,但现在当我将其排除在外时,该方法会立即返回 400 错误请求。 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.它并不漂亮,但我唯一能想到的(如果您不想发布任何正文)是使用 Jersey 的ContainerRequest ,您可以将其注入到方法中。 Then if there is any body, get the multipart as FormDataMultiPart and just traverse the parts manually.然后,如果有任何主体,则将多部分作为FormDataMultiPart获取,然后手动遍历这些部分。

@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) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Jersey REST API中使用多部分表单数据 - Consuming Multipart form data in Jersey REST API 泽西岛 - 包含文本正文部分的多部分数据表单 - Jersey - Multipart data form with text body parts 使用Jersey发送多个文件:找不到multipart / form-data的MessageBodyWriter - Sending multiple files with Jersey: MessageBodyWriter not found for multipart/form-data 如何自动将multipart / form-data输入映射到Jersey中的Bean - How to automatically map multipart/form-data input to a bean in Jersey 泽西岛2多部分/表单数据问题。 InputStream为空(可用= 0) - Jersey 2 multipart/form-data issue. InputStream is empty (available=0) 向Jersey多部分表单数据功能添加注释会破坏它 - Adding annotations to a Jersey multipart-form-data function breaks it Jersey API中的多部分/表单数据出现CORS错误 - CORS Error is coming for multipart/form-data in Jersey API 多部分/表格数据文件上传+泽西岛的其他参数 - multipart/form-data file upload + other parameters in Jersey Jersey:找不到媒体类型= multipart / form-data的MessageBodyReader - Jersey: MessageBodyReader not found for media type=multipart/form-data 如何使用org.glassfish.jersey.media.multipart从Java发送内容和文件作为多部分表单数据? - How to send content and file as Multipart Form Data from Java using org.glassfish.jersey.media.multipart?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM