Search code examples
javarestweb-servicesjersey

File Wrong Upload Jersey RestFull Service


I really can't understand the reason for this error. I ran the sample application. It works correctly. Same code but cannot load correctly. I think the error is due to the version difference. Anyone have any suggestions for a solution?

The web service I created

    @POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response getImageText( @FormDataParam("file")InputStream inputStream) { 
        try {
            byte[] bytes =IOUtils.toByteArray(inputStream);             
            inputStream.close();                
            System.out.println(bytes.length);           
             ArrayList<ImageBarcod> temp=null;
            return Response.ok(temp).build();
        } catch (Exception e) {
            return Response
                    .status(Response.Status.NOT_FOUND)
                    .build();               
        }   
}

bytes.length output:

enter image description here

file size to upload

enter image description here

sample application

enter image description here

upload file:

upload file

save file:

save file

Libraries:

Maven Libraries


Solution

  • The problem is that you are using Jersey 2.x, but your Multipart dependency is for Jersey 1.x. The two Jersey versions are incompatible. So the @FormDataParam annotation you using is just being ignored. That's why what you are getting in the InputStream is the entire multipart entity instead of just the file part.

    What you need to do is get rid of all your Jersey 1.x dependencies then add the Jersey 2.x jersey-media-multipart dependency.

    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>${jersey2.version}</version>
    </dependency>
    

    Then you need to register the MultiPartFeature with your application. You can see a few different ways to do that in this post. After you do that, you will be able to use the 2.x version of the @FormDataParam (which is different from the 1.x version).