【问题标题】:file downloading in restful web servicesRESTful Web 服务中的文件下载
【发布时间】:2012-04-23 11:06:21
【问题描述】:

我的要求是,我应该向客户端发送一个 10MB 的 zip 文件,并提供 RESTful 服务。我在论坛中发现发送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);
        }
     }
  };
}

【问题讨论】:

    标签: java rest


    【解决方案1】:

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

    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 中使用什么参考?我有 3 个潜在的参考。
    • @Lismore import javax.ws.rs.core.Response.ResponseBuilder; - 或者在你的源代码中使用Response.ResponseBuilder - 否则我遇到了和你一样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多