2012-04-11 14 views
13

मेरी आवश्यकता है, मुझे क्लाइंट को एक आरामदायक सेवा के साथ 10 एमबी ज़िप फ़ाइल भेजनी चाहिए। मैं मंचों में कोड है कि एक StreamingOutput वस्तु भेजने बेहतर तरीका है पाया है, लेकिन कैसे मैं निम्नलिखित कोड में एक StreamingOutput वस्तु बना सकते हैं:फ़ाइल को आराम से वेब सेवाओं में डाउनलोड करना

@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

इसका बेहतर तरीका और फ़ाइल 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(); 

} 

अपने कोड के लिए के रूप में आप से पूछा:

@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

मैं एक ऐसी ही आवेदन, कैसे आप के लिए aplcatio, अगर मैं http देते हैं, एक बाकी ग्राहक से फ़ाइल को प्राप्त करने जैसे हो रहा है?: // localhost: 8080/urapplication/मिलता है? – parameswar

+0

ResponseBuilder के लिए आप किस संदर्भ का उपयोग कर रहे हैं? मेरे पास 3 संभावित संदर्भ हैं। – Lismore

+1

@ लिस्मोर 'आयात javax.ws.rs.core.Response.ResponseBuilder;' - या अपने स्रोत में 'Response.ResponseBuilder' का उपयोग करें - अन्यथा मुझे आपके जैसा ही समस्या थी। –

संबंधित मुद्दे