2012-04-11 80 views
13

我的要求是,我應該向客戶端發送一個10MB的zip文件,並提供一個寧靜的服務。我發現在論壇上的代碼,發送StreamingOutput對象是更好的辦法,但我怎麼能在下面的代碼創建一個StreamingOutput對象:在寧靜的web服務中下載文件

@Path("PDF-file.pdf/") 
@GET 
@Produces({"application/pdf"}) 
public StreamingOutput getPDF() throws Exception { 
    return new StreamingOutput() { 
    public void write(OutputStream output) throws IOException, WebApplicationException  
    { 
     try { 
      //------ 
     } catch (Exception e) { 
      throw new WebApplicationException(e); 
     } 
    } 
    }; 
} 

回答

22

它是更好的方式和文件下載中心簡單的方法。

private static final String FILE_PATH = "d:\\Test2.zip"; 
@GET 
@Path("/get") 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public Response getFile() { 
    File file = new File(FILE_PATH); 
    ResponseBuilder response = Response.ok((Object) file); 
    response.header("Content-Disposition", "attachment; filename=newfile.zip"); 
    return response.build(); 

} 

爲您的代碼,你問:

@GET 
@Path("/helloWorldZip") 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public StreamingOutput helloWorldZip() throws Exception { 
    return new StreamingOutput(){ 
    @Override 
     public void write(OutputStream arg0) throws IOException, WebApplicationException { 
      // TODO Auto-generated method stub 
      BufferedOutputStream bus = new BufferedOutputStream(arg0); 
      try { 
       //ByteArrayInputStream reader = (ByteArrayInputStream) Thread.currentThread().getContextClassLoader().getResourceAsStream();  
       //byte[] input = new byte[2048]; 
       java.net.URL uri = Thread.currentThread().getContextClassLoader().getResource(""); 
       File file = new File("D:\\Test1.zip"); 
       FileInputStream fizip = new FileInputStream(file); 
       byte[] buffer2 = IOUtils.toByteArray(fizip); 
       bus.write(buffer2); 
      } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      } 
     } 
    }; 
} 
+1

我有一個類似的應用程序,如何從REST客戶端檢索文件,例如,你aplcatio,如果我給HTTP? // localhost:8080/urapplication/get? – parameswar 2013-10-09 19:01:57

+0

您對ResponseBuilder使用了什麼參考?我有3個潛在的參考。 – Lismore 2017-01-17 14:16:10

+1

@Lismore'import javax.ws.rs.core.Response.ResponseBuilder;' - 或者在源代碼中使用'Response.ResponseBuilder' - 否則我的問題和你一樣。 – 2018-01-24 09:37:17