2013-05-26 44 views
2

我想將一個二進制文件(圖片)發送到我在Glassfish中運行的REST風格的Web服務。 我發現代碼應該這樣做 Upload data method in REST web service 和其他幾個類似的帖子,但都沒有工作。 這是我的代碼:在Glassfish中使用REST風格的Web服務上傳二進制文件

@POST 
@Consumes(MediaType.APPLICATION_OCTET_STREAM) 
public String post(InputStream payload) throws IOException 
{ 
    return "Payload size="+payload.available(); 
} 

@POST 
@Path("bytes") 
@Consumes(MediaType.APPLICATION_OCTET_STREAM) 
public String post(byte[] payload) 
{ 
    return "Payload size="+payload.length; 
} 

接收的InputStream該方法返回:

Payload size=0 

接收字節[]回報的方法:

Error 500 - Internal Server Error 

的誤差500由此引起的例外:

Caused by: java.lang.NullPointerException 
at com.sun.jersey.moxy.MoxyMessageBodyWorker.typeIsKnown(MoxyMessageBodyWorker.java:110) 
at com.sun.jersey.moxy.MoxyMessageBodyWorker.isReadable(MoxyMessageBodyWorker.java:133) 
at com.sun.jersey.core.spi.factory.MessageBodyFactory._getMessageBodyReader(MessageBodyFactory.java:345) 
at com.sun.jersey.core.spi.factory.MessageBodyFactory._getMessageBodyReader(MessageBodyFactory.java:315) 
at com.sun.jersey.core.spi.factory.MessageBodyFactory.getMessageBodyReader(MessageBodyFactory.java:294) 
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:449) 
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123) 
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46) 
... 40 more 

任何意見,非常感謝。

+0

我強烈建議你刪除一個標籤以騰出空間給「java」 –

+0

@MrD好主意。完成。謝謝。 – Sergey

回答

2

我覺得APPLICATION_OCTET_STREAM工作,但payload.available()不能在這裏工作

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

你會發現確實的方法工作,因爲它打印一些字節。但是payload.available()是0.

+0

謝謝石質。我之前看過這個例子,但問題是客戶端沒有發送MediaType.MULTIPART_FORM_DATA - 它正在發送MediaType.APPLICATION_OCTET_STREAM,所以這個例子不適合我。有什麼辦法可以改變它消耗八位字節流? – Sergey

+0

我認爲APPLICATION_OCTET_STREAM正在工作,但payload.available()不能在這裏工作。我只是編輯我的答案,請檢查它。 – Stony

+0

是的,斯蒂尼,你是對的 - 它確實有效。非常感謝。 – Sergey