2012-04-11 2 views
13

Meine Anforderung ist, ich sollte eine 10MB Zip-Datei an den Client mit einem erholsamen Service senden. Ich fand den Code in Foren, die ein StreamingOutput Objekt zu senden ist der bessere Weg, aber wie kann ich ein StreamingOutput Objekt in dem folgenden Code erstellen:Datei herunterladen in erholsamen Web-Services

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

Antwort

22

Sein den besseren Weg und einfache Möglichkeit für Datei dowload.

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

} 

für Ihren Code, wie Sie gefragt:

@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

i eine ähnliche Anwendung habe, wie die Datei von einem REST-Client abgerufen werden zB für Sie aplcatio, wenn ich http geben?: // localhost: 8080/Anwendung/get? – parameswar

+0

Welche Referenz verwenden Sie für ResponseBuilder? Ich habe 3 mögliche Referenzen. – Lismore

+1

@Lismore 'importieren Sie javax.ws.rs.core.Response.ResponseBuilder;' - Oder verwenden Sie 'Response.ResponseBuilder' in Ihrer Quelle - sonst hatte ich das selbe Problem wie Sie. –