How to avoid OutOfMemoryError when uploading a large file using Jersey client

前端 未结 6 2107
难免孤独
难免孤独 2020-11-28 08:14

I am using Jersey client for http-based request. It works well if the file is small but run into error when I post a file with size of 700M:

Exception in thr         


        
6条回答
  •  一整个雨季
    2020-11-28 08:49

    In order for your code not to depend on the size of the uploaded file, you need:

    1. Use streams
    2. Define the chuck size of the jersey client. For example: client.setChunkedEncodingSize(1024);

    Server:

        @POST
        @Path("/upload/{attachmentName}")
        @Consumes(MediaType.APPLICATION_OCTET_STREAM)
        public void uploadAttachment(@PathParam("attachmentName") String attachmentName, InputStream attachmentInputStream) {
            // do something with the input stream
        }
    

    Client:

        ...
        client.setChunkedEncodingSize(1024);
        WebResource rootResource = client.resource("your-server-base-url");
        File file = new File("your-file-path");
        InputStream fileInStream = new FileInputStream(file);
        String contentDisposition = "attachment; filename=\"" + file.getName() + "\"";
        ClientResponse response = rootResource.path("attachment").path("upload").path("your-file-name")
                .type(MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", contentDisposition)
                .post(ClientResponse.class, fileInStream);
    

提交回复
热议问题