gpt4 book ai didi

java - 在 Restful Web 服务中下载文件

转载 作者:行者123 更新时间:2023-12-02 07:43:45 25 4
gpt4 key购买 nike

我的要求是,我应该通过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);
}
}
};
}

最佳答案

这是文件下载的更好、更简单的方法。

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

关于java - 在 Restful Web 服务中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10100936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com