Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

java - file downloading in restful web services

My requirement is, I should send a 10MB zip file to the client with a restful service. I found the code in forums that sending a StreamingOutput object is the better way, but how can I create a StreamingOutput object in the following code:

@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);
        }
     }
  };
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Its the better way and easy way for 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();

}

For your code as you asked:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...