RESTeasy client code for attaching a file

后端 未结 1 1959
情深已故
情深已故 2020-12-17 04:48

I need to attach a file to my service end-point . I tested the functionality via POSTMAN ( chrome browser plugin to test rest service ) , it is working fine.

But I n

相关标签:
1条回答
  • 2020-12-17 05:24

    Multipart has a special format. If the server is expecting a multipart/form-data format, we can't just send it as a normal request. You can look at the preview window in Postman to see the format

    enter image description here enter image description here


    You can see that each part has a boundary. We don't really have to worry about setting this manually. Resteasy has an API for building multiform output. You can use the MultipartFormDataOutput class to build the output. Just use the addFormData method to add parts. In your case its only one part, but the request will still get formatted the way the server is expecting.

    So your request should look something more like

    MultipartFormDataOutput output = new MultipartFormDataOutput();
                          // file (below) doesn't have to be a `byte[]`
                          // It can be a `File` object and work just the same
    output.addFormData("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE);
    
    Response response = target.request()
            .post(Entity.entity(output, MediaType.MULTIPART_FORM_DATA));
    

    This is assuming you have the required dependency, as I imaging you would, if the server is accepting multipart

    <dependency>
       <groupId>org.jboss.resteasy</groupId>
       <artifactId>resteasy-multipart-provider</artifactId>
       <version>${resteasy.version}</version>
    </dependency>
    

    • See more about Output with multipart/form-data

    And just for completeness...

    For any future readers who are curious about server side (since you haven't provided your code), this is what I used to test

    @Path("/multipart")
    public class MultipartResource {
    
        @POST
        @Consumes(MediaType.MULTIPART_FORM_DATA)
        public Response postData(MultipartFormDataInput input) throws Exception {
    
            byte[] bytes = input.getFormDataPart("file", byte[].class, null);
            JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bytes)));
    
            return Response.ok("GOT IT").build();
        }
    }
    
    0 讨论(0)
提交回复
热议问题