2012-04-11 44 views
13

Yêu cầu của tôi là, tôi nên gửi tệp zip 10MB cho khách hàng bằng dịch vụ an toàn. Tôi tìm thấy đoạn code trên các diễn đàn rằng việc gửi một đối tượng StreamingOutput là cách tốt hơn, nhưng làm thế nào tôi có thể tạo ra một đối tượng StreamingOutput trong đoạn mã sau:tải xuống tệp trong các dịch vụ web an toàn

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

Trả lời

22

của nó một cách tốt hơn và dễ dàng cho file 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(); 

} 

Đối với mã của bạn khi bạn hỏi:

@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

tôi đang có một ứng dụng tương tự, làm thế nào để lấy các tập tin từ một khách hàng REST của ví dụ, cho bạn aplcatio, nếu tôi cho http: // localhost: 8080/urapplication/get? – parameswar

+0

Bạn đang sử dụng tham chiếu nào cho ResponseBuilder? Tôi có 3 tài liệu tham khảo tiềm năng. – Lismore

+1

@Lismore 'nhập javax.ws.rs.core.Response.ResponseBuilder;' - Hoặc sử dụng 'Response.ResponseBuilder' trong nguồn của bạn - nếu không tôi cũng gặp vấn đề tương tự như bạn. –

Các vấn đề liên quan