上传大文件时Jersey2 Client OutOfMemoryError

时间:2016-06-23 12:33:12

标签: java jersey out-of-memory jax-rs jersey-client

我正在使用下面的代码处理fileupload,但在上传超过300 MB的文件时,我收到了OutOfMemoryError。

这是我的代码

package com.actifio.service.foresight;

import java.io.File;
import java.io.IOException;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;

public class UploadFileTest {
    public static void main(String[] args) throws IOException {
        final Client client = ClientBuilder.newBuilder()
                .register(MultiPartFeature.class).build();

        final FileDataBodyPart filePart = new FileDataBodyPart("file",
                new File("C:/temp/sample.pdf"));
        FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
        final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
                .field("foo", "bar").bodyPart(filePart);

        final WebTarget target = client
                .target("http://localhost:8080/JerseyDemos/rest/upload/pdf");
        final Response response = target.request().post(
                Entity.entity(multipart, multipart.getMediaType()));

        // Use response object to verify upload success

        formDataMultiPart.close();
        multipart.close();
    }
}

但是我得到Java堆空间异常,请查看下面的更多详细信息

javax.ws.rs.ProcessingException: Java heap space
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:263)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:671)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:668)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at 

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您应该使用chunks和流:

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(FormDataMultiPart formDataMultiPart) {
     FormDataBodyPart filePart = formDataMultiPart.getField("file");         
     InputStream fileInputStream = filePart.getValueAs(InputStream.class);
     .
     .
     .
}