Send File as a parameter to a REST Service, from a client?

后端 未结 2 431
感情败类
感情败类 2021-02-10 18:34

My Requirement is to send the file to the REST Service through one client. That service is going to process the file. I am using Jersey API for implementing this. But I have sea

2条回答
  •  难免孤独
    2021-02-10 19:21

    Assuming you are using Jersey on both the client and server side, here is some code that you can extend:

    Server side:

    @POST
    @Path("/")
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(final MimeMultipart file) {
        if (file == null)
            return Response.status(Status.BAD_REQUEST)
                    .entity("Must supply a valid file").build();
    
        try {
            for (int i = 0; i < file.getCount(); i++) {
                System.out.println("Body Part: " + file.getBodyPart(i));
            }
            return Response.ok("Done").build();
        } catch (final Exception e) {
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e)
                    .build();
        }
    }
    

    The above code implements a resource method that accepts POST's of multipart (file) data. It also illustrates how you can iterate through all the individual body parts in the incoming (multipart) request.

    Client:

    final ClientConfig config = new DefaultClientConfig();
    final Client client = Client.create(config);
    
    final WebResource resource = client.resource(ENDPOINT_URL);
    
    final MimeMultipart request = new MimeMultipart();
    request.addBodyPart(new MimeBodyPart(new FileInputStream(new File(
            fileName))));
    
    final String response = resource
        .entity(request, "multipart/form-data")
        .accept("text/plain")
        .post(String.class);
    

    The above code simply attaches a file to a multipart request, and fires the request off to the server. For both client and server side code there is a reliance on the Jersey and JavaMail libraries. If you are using Maven, these can be pulled down with ease, with the following dependencies:

    
        com.sun.jersey
        jersey-core
        1.17
    
    
     
        com.sun.jersey
        jersey-server
        1.14
    
    
     
        com.sun.jersey
        jersey-client
        1.17
    
    
    
        com.sun.jersey
        jersey-json
        1.17
    
    
    
        javax.mail
        mail
        1.4.6
    
    

    Adjust the dependency versions as required

提交回复
热议问题