用Jersey 2上传文件

时间:2015-12-23 16:02:40

标签: java rest file-upload jersey-2.0

我需要使用Jersey 2

通过休息呼叫上传二进制文件

我写了以下课程:

@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();
    }

}

当我尝试执行以下操作时:

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

我收到以下回复:

<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>

我哪里错了?

3 个答案:

答案 0 :(得分:0)

您应该使用MediaType.MULTIPART_FORM_DATA向Jersey指示您要接收的内容是文件。此外,你必须提示&#39;球衣哪个领域应该是你想要阅读的领域。更正后的版本将是:

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

请注意,MediaType.APPLICATION_OCTET_STREAM是通用MediaType。有关更详细的说明,请查看:Do I need Content-Type: application/octet-stream for file download?

答案 1 :(得分:0)

我已经解决了删除@Consumes注释的问题。

喜欢这个

public String uploadStream(InputStream payload) throws IOException {}

答案 2 :(得分:0)

服务器端看起来没问题。添加错误中所述的内容mime类型为我解决了问题:

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