2012-04-11 8 views
13

Mi requisito es, debo enviar un archivo zip de 10 MB al cliente con un servicio de descanso. He encontrado el código en los foros que el envío de un objeto StreamingOutput es la mejor manera, pero ¿cómo puedo crear un objeto StreamingOutput en el siguiente código:descarga de archivos en servicios web de descanso

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

Respuesta

22

Es la mejor forma y manera fácil para dowload archivo.

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

} 

Para su código a medida que preguntó:

@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

estoy teniendo una aplicación similar, la forma de recuperar el archivo desde un cliente REST por ejemplo, para que aplcatio, si me dan http: // localhost: 8080/urapplication/get? – parameswar

+0

¿Qué referencia está utilizando para ResponseBuilder? Tengo 3 referencias potenciales. – Lismore

+1

@Lismore 'import javax.ws.rs.core.Response.ResponseBuilder;' - O use 'Response.ResponseBuilder' en su fuente; de ​​lo contrario, tengo el mismo problema que usted. –