繁体   English   中英

文件与 Jersey 宁静网络服务中的其他对象一起上传

[英]File upload along with other object in Jersey restful web service

我想通过上传图像和员工数据在系统中创建员工信息。 我可以使用球衣通过不同的休息电话来做到这一点。 但我想在一次休息电话中实现。 我提供下面的结构。 请帮我这方面怎么做。

@POST
@Path("/upload2")
@Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response uploadFileWithData(
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
        Employee emp) {

//..... business login

}

每当我尝试这样做时,Chrome 邮递员都会出错。 下面给出了我的 Employee json 的简单结构。

{
    "Name": "John",
    "Age": 23,
    "Email": "john@gmail.com",
    "Adrs": {
        "DoorNo": "12-A",
        "Street": "Street-11",
        "City": "Bangalore",
        "Country": "Karnataka"
    }
}

但是,我可以通过拨打两个不同的电话来实现,但我想在一个休息电话中实现,以便我可以接收文件以及员工的实际数据。

请求您在这方面提供帮助。

你不能有两个Content-Type s(技术上这就是我们在下面所做的,但它们与 multipart 的每个部分分开,但主要类型是 multipart )。 这基本上就是您对方法的期望。 您期望 mutlipartjson 一起作为主要媒体类型。 Employee数据需要是 multipart 的一部分。 所以你可以为Employee添加一个@FormDataParam("emp")

@FormDataParam("emp") Employee emp) { ...

这是我用于测试的类

@Path("/multipart")
public class MultipartResource {
    
    @POST
    @Path("/upload2")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response uploadFileWithData(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition cdh,
            @FormDataParam("emp") Employee emp) throws Exception{
        
        Image img = ImageIO.read(fileInputStream);
        JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(img)));
        System.out.println(cdh.getName());
        System.out.println(emp);
        
        return Response.ok("Cool Tools!").build();
    } 
}

首先,我只是用客户端 API 进行了测试,以确保它可以正常工作

@Test
public void testGetIt() throws Exception {
    
    final Client client = ClientBuilder.newBuilder()
        .register(MultiPartFeature.class)
        .build();
    WebTarget t = client.target(Main.BASE_URI).path("multipart").path("upload2");

    FileDataBodyPart filePart = new FileDataBodyPart("file", 
                                             new File("stackoverflow.png"));
    // UPDATE: just tested again, and the below code is not needed.
    // It's redundant. Using the FileDataBodyPart already sets the
    // Content-Disposition information
    filePart.setContentDisposition(
            FormDataContentDisposition.name("file")
                                    .fileName("stackoverflow.png").build());

    String empPartJson
            = "{"
            + "  \"id\": 1234,"
            + "  \"name\": \"Peeskillet\""
            + "}";

    MultiPart multipartEntity = new FormDataMultiPart()
            .field("emp", empPartJson, MediaType.APPLICATION_JSON_TYPE)
            .bodyPart(filePart);
          
    Response response = t.request().post(
            Entity.entity(multipartEntity, multipartEntity.getMediaType()));
    System.out.println(response.getStatus());
    System.out.println(response.readEntity(String.class));

    response.close();
}

我刚刚创建了一个带有idname字段的简单Employee类用于测试。 这工作得很好。 它显示图像,打印内容配置,并打印Employee对象。

我对 Postman 不太熟悉,所以我把那个测试留到最后 :-)

在此处输入图片说明

它似乎也工作正常,因为您可以看到响应"Cool Tools" 但是如果我们查看打印的Employee数据,我们会发现它是 null。 这很奇怪,因为使用客户端 API 时它运行良好。

如果我们查看“预览”窗口,就会看到问题

在此处输入图片说明

emp正文部分没有Content-Type标头。 您可以在客户端 API 中看到我明确设置了它

MultiPart multipartEntity = new FormDataMultiPart()
        .field("emp", empPartJson, MediaType.APPLICATION_JSON_TYPE)
        .bodyPart(filePart);

所以我想这实际上只是完整答案的一部分 就像我说的,我不熟悉 Postman 所以我不知道如何为各个身体部位设置Content-Type image/png是自动为我设置的图像部分(我猜这只是由文件扩展名决定的)。 如果你能弄清楚这一点,那么问题就应该解决了。 请,如果您知道如何执行此操作,请将其发布为答案。

请参阅下面的更新以获取解决方案


只是为了完整性......

基本配置:

依赖:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey2.version}</version>
</dependency>

客户端配置:

final Client client = ClientBuilder.newBuilder()
    .register(MultiPartFeature.class)
    .build();

服务器配置:

// Create JAX-RS application.
final Application application = new ResourceConfig()
    .packages("org.glassfish.jersey.examples.multipart")
    .register(MultiPartFeature.class);

如果您在服务器配置方面遇到问题,以下帖子之一可能会有所帮助


更新

所以正如你从 Postman 客户端看到的,一些客户端无法设置单个部件的 Content-Type,这包括浏览器,关于它在使用FormData (js) 时的默认功能。

我们不能指望客户端解决这个问题,所以我们可以做的是,在接收数据时,在反序列化之前显式设置 Content-Type。 例如

@POST
@Path("upload2")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFileAndJSON(@FormDataParam("emp") FormDataBodyPart jsonPart,
                                  @FormDataParam("file") FormDataBodyPart bodyPart) { 
     jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
     Employee emp = jsonPart.getValueAs(Employee.class);
}

获得 POJO 需要一些额外的工作,但它比强迫客户端尝试找到自己的解决方案更好。

另一种选择是使用 String 参数并使用您用来将 String 反序列化为 POJO 的任何 JSON 库(如 Jackson ObjectMapper)。 使用前一个选项,我们只让 Jersey 处理反序列化,它将使用与所有其他 JSON 端点相同的 JSON 库(这可能是首选)。


旁白

  • 如果您使用的连接器与默认的 HttpUrlConnection 不同,那么您可能会对这些评论中的某个对话感兴趣。

您可以使用 MULTIPART FORM DATA 从表单访问图像文件和数据,使用以下代码。

@POST
@Path("/UpdateProfile")
@Consumes(value={MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA})
@Produces(value={MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response updateProfile(
    @FormDataParam("file") InputStream fileInputStream,
    @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
    @FormDataParam("ProfileInfo") String ProfileInfo,
    @FormDataParam("registrationId") String registrationId) {

    String filePath= "/filepath/"+contentDispositionHeader.getFileName();

    OutputStream outputStream = null;
    try {
        int read = 0;
        byte[] bytes = new byte[1024];
        outputStream = new FileOutputStream(new File(filePath));

        while ((read = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) { 
            try {
                outputStream.close();
            } catch(Exception ex) {}
        }
    }
}

当我在 Jersey 客户端2.21.1 上尝试@PaulSamsotha 的解决方案时,出现了 400 错误。 当我在客户端代码中添加以下内容时它起作用了:

MediaType contentType = MediaType.MULTIPART_FORM_DATA_TYPE;
contentType = Boundary.addBoundary(contentType);

Response response = t.request()
        .post(Entity.entity(multipartEntity, contentType));

而不是在 POST 请求调用中硬编码MediaType.MULTIPART_FORM_DATA

之所以需要这样做,是因为当您为 Jersey 客户端使用不同的连接器(如 Apache)时,它无法更改出站标头,这是向 Content-Type 添加边界所必需的。 Jersey 客户端文档中解释了此限制。 所以如果你想使用不同的Connector,那么你需要手动创建边界。

您的 ApplicationConfig 应该从 glassfish.jersey.media.. 注册 MultiPartFeature.class 以启用文件上传

@javax.ws.rs.ApplicationPath(ResourcePath.API_ROOT)
public class ApplicationConfig extends ResourceConfig {  
public ApplicationConfig() {
        //register the necessary headers files needed from client
        register(CORSConfigurationFilter.class);
        //The jackson feature and provider is used for object serialization
        //between client and server objects in to a json
        register(JacksonFeature.class);
        register(JacksonProvider.class);
        //Glassfish multipart file uploader feature
        register(MultiPartFeature.class);
        //inject and registered all resources class using the package
        //not to be tempered with
        packages("com.flexisaf.safhrms.client.resources");
        register(RESTRequestFilter.class);
    }

请求类型是多部分/表单数据,您发送的本质上是表单字段,这些字段以字节形式输出,内容边界分隔不同的表单字段。要将对象表示作为表单字段(字符串)发送,您可以从然后您可以在服务器上反序列化的客户端。

毕竟,实际上没有任何编程环境对象是在线上传输的。 两边的编程环境都只是在做你也可以做的自动序列化和反序列化。 这是最干净和编程环境怪癖免费的方式来做到这一点。

举个例子,这是一个 javascript 客户端发布到 Jersey 示例服务,

submitFile(){

    let data = new FormData();
    let account = {
        "name": "test account",
        "location": "Bangalore"
    }

    data.append('file', this.file);
    data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
    data.append("device", "test001");
    data.append("account", JSON.stringify(account));
    
    let url = "http://localhost:9090/sensordb/test/file/multipart/upload";

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios.post(url, data, config).then(function(data){
        console.log('SUCCESS!!');
        console.log(data.data);
    }).catch(function(){
        console.log('FAILURE!!');
    });
},

在这里,客户端正在发送一个文件、2 个表单字段(字符串)和一个已为传输字符串化的帐户对象。 这是表单字段在电线上的外观,

在此处输入图片说明

在服务器上,您可以按照您认为合适的方式反序列化表单字段。 为了完成这个简单的例子,

    @POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh,
        @FormDataParam("accountKey") String accountKey,
        @FormDataParam("account") String json)  {
    

    
    System.out.println(cdh.getFileName());
    System.out.println(cdh.getName());
    System.out.println(accountKey);
    
    try {
        Account account = Account.deserialize(json);
        System.out.println(account.getLocation());
        System.out.println(account.getName());
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return Response.ok().build();
    
}

我使用了文件上传示例,

http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/

在我的资源类中,我有以下方法

@POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response  attachupload(@FormDataParam("file") byte[] is,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("fileName") String flename){
attachService.saveAttachment(flename,is);
}

在我的 attachService.java 中,我有以下方法

 public void saveAttachment(String flename,  byte[] is) {
            // TODO Auto-generated method stub
         attachmentDao.saveAttachment(flename,is);

        }

在道我有

attach.setData(is);
attach.setFileName(flename);

在我的 HBM 映射中

<property name="data" type="binary" >
            <column name="data" />
</property>

这适用于所有类型的文件,如 .PDF、.TXT、.PNG 等,

暂无
暂无

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

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