Reputation: 287
I am working on fileupload using below code but while uploading more than 300 MB file, I am getting OutOfMemoryError.
Here's my code below
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();
}
}
But I am getting Java heap space Exception, check below for more details
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
Can anyone help me on this issue?
Upvotes: 4
Views: 1709
Reputation: 61
You should use chunks and streams:
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(FormDataMultiPart formDataMultiPart) {
FormDataBodyPart filePart = formDataMultiPart.getField("file");
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
.
.
.
}
Upvotes: 2