在宁静的Web服务中下载文件 [英] file downloading in restful web services

查看:146
本文介绍了在宁静的Web服务中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是,我应该向客户发送一个10MB的zip文件,并提供宁静的服务。我在论坛中发现发送 StreamingOutput 对象的代码是更好的方法,但是如何创建 StreamingOutput 对象在以下代码中:

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


推荐答案

它更好的方式和简单文件下载的方式。

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

这篇关于在宁静的Web服务中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆