2

I need to upload a binary file through a rest call using Jersey 2

I have write the following class:

@Path("/entry-point")
public class EntryPoint {

    @POST
    @Path("/upload")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    public String uploadStream( InputStream payload ) throws IOException
    {
        while(true) {
            try {
                DataInputStream dis = new DataInputStream(payload);
                System.out.println(dis.readByte());
            } catch (Exception e) {
                break;
            }
        }
        //Or you can save the inputsream to a file directly, use the code, but must remove the while() above.
        /**
         OutputStream os =new FileOutputStream("C:\recieved.jpg");
         IOUtils.copy(payload,os);
         **/
        System.out.println("Payload size="+payload.available());
        return "Payload size="+payload.available();
    }

}

When I try to do something like the following:

curl --request POST --data-binary "@file.txt" http://localhost:8080/entry-point/upload

I get the following response:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 415 </title>
</head>
<body>
<h2>HTTP ERROR: 415</h2>
<p>Problem accessing /entry-point/up. Reason:
<pre>    Unsupported Media Type</pre></p>
<hr /><a href="http://eclipse.org/jetty">Powered by Jetty:// 9.3.6.v20151106</a><hr/>
</body>
</html>

Where am I wrong?

theShadow89
  • 1,307
  • 20
  • 44

3 Answers3

1

Server side looks OK. Adding the content mime type as stated in the error solved the issue for me:

-H 'Content-Type: application/octet-stream'

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
0

You should use MediaType.MULTIPART_FORM_DATA to indicate to Jersey that what you are going to receive is a file. In addition, you have to 'hint' jersey which field should be the one you want to read. A corrected version would be :

 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public String uploadStream( @FormDataParam("file") InputStream payload ) throws IOException {

Note that MediaType.APPLICATION_OCTET_STREAM is a generic MediaType. For a more detailed explanation check : Do I need Content-Type: application/octet-stream for file download?

Community
  • 1
  • 1
Louis F.
  • 2,018
  • 19
  • 22
  • Did you try to add as header the multipart/form-data Content-Type such as : `curl --request POST --data-binary "@file.txt" http://localhost:8080/entry-point/upload -H 'Content-Type: multipart/form-data'` – Louis F. Dec 23 '15 at 21:53
  • Sorry for late. I was in vacation. I have try your call and now I get `Error 400 Bad Request` – theShadow89 Jan 04 '16 at 11:18
0

I have resolved removing @Consumes annotation.

Like this

public String uploadStream(InputStream payload) throws IOException {}
theShadow89
  • 1,307
  • 20
  • 44