2015-07-03 34 views
0

在我的服务器端,我有一个图像,将通过其余的发送到客户端 发送后,图像应该被删除。启用发送图像作为Fileoutputstream通过resteasy

所以图像将被复制到fileoutputstream,我发送fileoutputstream到客户端,我删除图像。

我使用下面的代码:

@GET 
@Path("/get_image") 
@Produces({ MediaType.APPLICATION_OCTET_STREAM })  
public Response getImage(){ 

....... 

    File image = new File("myimage.png"); 
    FileOutputStream oos = new FileOutputStream("imageToSend.png"); 
    byte[] buf = new byte[8192]; 
      InputStream is = new FileInputStream(image); 
      int c = 0; 
      while ((c = is.read(buf, 0, buf.length)) > 0) { 
       oos.write(buf, 0, c); 
       oos.flush(); 
      } 

      ResponseBuilder response = Response.ok(oos); 
      response.header("Content-Disposition", 
        "attachment; filename=image.png"); 
      oos.close(); 
      is.close(); 

      image.delete(); 

      return response.build(); 
     } 
    } 

,但是当我执行的getImage方法,我发现这个错误

org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: java.io.FileOutputStream of media type: application/octet-stream 
    at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:67) 
    at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:411) 

如果任何一个有关于这个问题的原因想法....

亲切的问候

+0

你期望Resteasy如何处理输出流?它无法读取它,并且没有接口来获取流所代表的文件。 – Kenster

+0

@Kenster,我想删除它发送后的图像: 'File image = new File(pathImage); ResponseBuilder response = Response.ok((Object)image); response.header(“Content-Disposition”, \t \t \t \t“attachment; filename = tsunami_image.png”); image.delete() return response.build();' 如果我在响应中设置图像对象,并删除图像,我得到** fileNotFoundExeption **错误。然后根据我在网上的研究,他们建议直接写输出流作为回应,然后你可以删除文件。但我一直无法做到这一点.... –

+0

也许你可以分享一些你发现的有关将输出流传递给resteasy的研究。 – Kenster

回答

0

您应该只使用InputStream作为响应主体(RESTeasy将为您编写代码),或者您可以使用StreamingOutput将数据直接写入响应流。例如,

StreamingOutput output = new StreamingOutput() { 
    @Override 
    public void write(OutputStream out) { 
     InputStream is = new FileInputStream(image); 
     int c = 0; 
     while ((c = is.read(buf, 0, buf.length)) > 0) { 
      oos.write(buf, 0, c); 
      oos.flush(); 
     } 
     is.close(); 
    } 
} 

ResponseBuilder response = Response.ok(output); 

它可能只是更容易使用返回InputStream而不是。它几乎做了同样的事情,因为使用上面的StreamingOutput。我过去遇到过的一件奇怪事情是在尝试返回InputStream时遇到大文件。与StreamingOutput,它似乎更好。