简体   繁体   中英

Upload File with Jersey 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?

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?

I have resolved removing @Consumes annotation.

Like this

public String uploadStream(InputStream payload) throws IOException {}

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM