将输出流传递给javax.ws.rs.core.ResponseBuilder

时间:2020-02-18 08:43:52

标签: java rest jax-rs

我的问题是是否/如何将OutputStream传递给Jax-rs中的Response-Object。这是我当前设置的(非结构化)描述:

我有一个基于Java的REST服务(基于Java Jax-rs的resteasy实现)。可以使用Web浏览器访问该api,并且后端有一些发出OutputStream的服务。此OutputStream的结果以文件下载的形式提供。要将数据从OutputStream传输到浏览器,我将OutputStream的输出存储在文件系统中,然后使用ResponsBuilderStreamingOutput将数据传输到浏览器/用户。文件创建是我要避免的(真的没有特殊原因-我只是认为避免文件创建更好...)。这是将创建的文件传递到responsebuilder并随后将其删除的代码:

// <SNIP>
StreamingOutput fileStream = new StreamingOutput() {
                @Override
                public void write(OutputStream output) throws IOException, WebApplicationException {
                    try {
                        Files.copy(exportedFile.toPath(), output);
                    } catch (NoSuchFileException e) {
                        logger.error("An exception (NoSuchFile) occured. MESSAGE=" + e.getMessage());
                    }
                    finally {
                        Files.delete(exportedFile.toPath());
                    }
                }
            };

response = Response.ok( fileStream , MediaType.APPLICATION_OCTET_STREAM )
                    .header("content-disposition","attachment; filename = download.dat"))
                    .build();

return response;
// <SNIP>

1 个答案:

答案 0 :(得分:0)

虽然我完全固定在一个听起来像“嘿,响应,这是您的输出流。请把它传递给用户,别忘了以后再关闭流”的解决方案,但这样做似乎没有问题

StreamingOutput fileStream = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {

                myResult.write(output);
                myResult.close();

            }

        };