在RESTful Web服务中文件下载

26

我的需求是,我需要通过一个restful服务向客户端发送一个10MB的zip文件。我在论坛上找到了发送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);
        }
     }
  };
}
1个回答

41

这是更好且更容易的下载文件的方法。

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

你在使用哪个 ResponseBuilder 的引用?我有三个可能的引用。 - Lismore
1
@Lismore import javax.ws.rs.core.Response.ResponseBuilder; - 或者在你的源代码中使用 Response.ResponseBuilder - 否则我和你遇到了同样的问题。 - Falco Preiseni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接