114

我正在使用 Jersey 来实现一个 RESTful API,它主要用于检索和提供 JSON 编码的数据。但是我在某些情况下需要完成以下操作:

  • 导出可下载的文档,例如 PDF、XLS、ZIP 或其他二进制文件。
  • 检索多部分数据,例如一些 JSON 加上上传的 XLS 文件

我有一个基于 JQuery 的单页 Web 客户端,它创建对此 Web 服务的 AJAX 调用。目前,它不进行表单提交,并使用 GET 和 POST(带有 JSON 对象)。我应该使用表单发布来发送数据和附加的二进制文件,还是可以使用 JSON 和二进制文件创建多部分请求?

我的应用程序的服务层当前在生成 PDF 文件时会创建一个 ByteArrayOutputStream。通过 Jersey 将此流输出到客户端的最佳方式是什么?我创建了一个 MessageBodyWriter,但我不知道如何从 Jersey 资源中使用它。这是正确的方法吗?

我一直在查看 Jersey 附带的示例,但还没有找到任何可以说明如何做这些事情的东西。如果重要的话,我正在使用 Jersey 和 Jackson 来执行 Object->JSON 而不使用 XML 步骤,并且没有真正使用 JAX-RS。

4

10 回答 10

110

我设法通过扩展StreamingOutput对象来获取 ZIP 文件或 PDF 文件。这是一些示例代码:

@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 {
                PDFGenerator generator = new PDFGenerator(getEntity());
                generator.generatePDF(output);
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}

PDFGenerator 类(我自己的用于创建 PDF 的类)从 write 方法获取输出流并将其写入该方法,而不是新创建的输出流。

不知道这是否是最好的方法,但它确实有效。

于 2010-08-17T14:48:04.080 回答
30

我不得不返回一个 rtf 文件,这对我有用。

// create a byte array of the file in correct format
byte[] docStream = createDoc(fragments); 

return Response
            .ok(docStream, MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition","attachment; filename = doc.rtf")
            .build();
于 2010-10-22T22:34:26.390 回答
23

我正在使用此代码将球衣中的 excel (xlsx) 文件 ( Apache Poi ) 作为附件导出。

@GET
@Path("/{id}/contributions/excel")
@Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
public Response exportExcel(@PathParam("id") Long id)  throws Exception  {

    Resource resource = new ClassPathResource("/xls/template.xlsx");

    final InputStream inp = resource.getInputStream();
    final Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);

    Row row = CellUtil.getRow(7, sheet);
    Cell cell = CellUtil.getCell(row, 0);
    cell.setCellValue("TITRE TEST");

    [...]

    StreamingOutput stream = new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                wb.write(output);
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };


    return Response.ok(stream).header("content-disposition","attachment; filename = export.xlsx").build();

}
于 2012-04-02T10:59:09.023 回答
16

这是另一个例子。我正在通过 ByteArrayOutputStream. 资源返回一个Response对象,流的数据就是实体。

为了说明响应代码处理,我添加了对缓存头(If-modified-since、、If-none-matches等)的处理。

@Path("{externalId}.png")
@GET
@Produces({"image/png"})
public Response getAsImage(@PathParam("externalId") String externalId, 
        @Context Request request) throws WebApplicationException {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    // do something with externalId, maybe retrieve an object from the
    // db, then calculate data, size, expirationTimestamp, etc

    try {
        // create a QRCode as PNG from data     
        BitMatrix bitMatrix = new QRCodeWriter().encode(
                data, 
                BarcodeFormat.QR_CODE, 
                size, 
                size
        );
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);

    } catch (Exception e) {
        // ExceptionMapper will return HTTP 500 
        throw new WebApplicationException("Something went wrong …")
    }

    CacheControl cc = new CacheControl();
    cc.setNoTransform(true);
    cc.setMustRevalidate(false);
    cc.setNoCache(false);
    cc.setMaxAge(3600);

    EntityTag etag = new EntityTag(HelperBean.md5(data));

    Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(
            updateTimestamp,
            etag
    );
    if (responseBuilder != null) {
        // Preconditions are not met, returning HTTP 304 'not-modified'
        return responseBuilder
                .cacheControl(cc)
                .build();
    }

    Response response = Response
            .ok()
            .cacheControl(cc)
            .tag(etag)
            .lastModified(updateTimestamp)
            .expires(expirationTimestamp)
            .type("image/png")
            .entity(stream.toByteArray())
            .build();
    return response;
}   

请不要打我,以防万一stream.toByteArray()是不明智的:) 它适用于我的 <1KB PNG 文件...

于 2012-09-24T21:27:00.380 回答
14

我一直在按以下方式编写我的 Jersey 1.17 服务:

FileStreamingOutput

public class FileStreamingOutput implements StreamingOutput {

    private File file;

    public FileStreamingOutput(File file) {
        this.file = file;
    }

    @Override
    public void write(OutputStream output)
            throws IOException, WebApplicationException {
        FileInputStream input = new FileInputStream(file);
        try {
            int bytes;
            while ((bytes = input.read()) != -1) {
                output.write(bytes);
            }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
            if (output != null) output.close();
            if (input != null) input.close();
        }
    }

}

GET

@GET
@Produces("application/pdf")
public StreamingOutput getPdf(@QueryParam(value="name") String pdfFileName) {
    if (pdfFileName == null)
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    if (!pdfFileName.endsWith(".pdf")) pdfFileName = pdfFileName + ".pdf";

    File pdf = new File(Settings.basePath, pdfFileName);
    if (!pdf.exists())
        throw new WebApplicationException(Response.Status.NOT_FOUND);

    return new FileStreamingOutput(pdf);
}

和客户,如果你需要它:

Client

private WebResource resource;

public InputStream getPDFStream(String filename) throws IOException {
    ClientResponse response = resource.path("pdf").queryParam("name", filename)
        .type("application/pdf").get(ClientResponse.class);
    return response.getEntityInputStream();
}
于 2013-10-31T09:05:23.853 回答
7

使用 Jersey 2.16 文件下载非常容易。

以下是 ZIP 文件的示例

@GET
@Path("zipFile")
@Produces("application/zip")
public Response getFile() {
    File f = new File(ZIP_FILE_PATH);

    if (!f.exists()) {
        throw new WebApplicationException(404);
    }

    return Response.ok(f)
            .header("Content-Disposition",
                    "attachment; filename=server.zip").build();
}
于 2015-02-12T14:12:33.460 回答
7

这个例子展示了如何通过一个 rest 资源在 JBoss 中发布日志文件。请注意,get 方法使用 StreamingOutput 接口来流式传输日志文件的内容。

@Path("/logs/")
@RequestScoped
public class LogResource {

private static final Logger logger = Logger.getLogger(LogResource.class.getName());
@Context
private UriInfo uriInfo;
private static final String LOG_PATH = "jboss.server.log.dir";

public void pipe(InputStream is, OutputStream os) throws IOException {
    int n;
    byte[] buffer = new byte[1024];
    while ((n = is.read(buffer)) > -1) {
        os.write(buffer, 0, n);   // Don't allow any extra bytes to creep in, final write
    }
    os.close();
}

@GET
@Path("{logFile}")
@Produces("text/plain")
public Response getLogFile(@PathParam("logFile") String logFile) throws URISyntaxException {
    String logDirPath = System.getProperty(LOG_PATH);
    try {
        File f = new File(logDirPath + "/" + logFile);
        final FileInputStream fStream = new FileInputStream(f);
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                try {
                    pipe(fStream, output);
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return Response.ok(stream).build();
    } catch (Exception e) {
        return Response.status(Response.Status.CONFLICT).build();
    }
}

@POST
@Path("{logFile}")
public Response flushLogFile(@PathParam("logFile") String logFile) throws URISyntaxException {
    String logDirPath = System.getProperty(LOG_PATH);
    try {
        File file = new File(logDirPath + "/" + logFile);
        PrintWriter writer = new PrintWriter(file);
        writer.print("");
        writer.close();
        return Response.ok().build();
    } catch (Exception e) {
        return Response.status(Response.Status.CONFLICT).build();
    }
}    

}

于 2013-07-10T16:38:40.877 回答
5

我发现以下内容对我有帮助,我想分享一下,以防它对您或其他人有所帮助。我想要类似 MediaType.PDF_TYPE 的东西,它不存在,但这段代码做同样的事情:

DefaultMediaTypePredictor.CommonMediaTypes.
        getMediaTypeFromFileName("anything.pdf")

请参阅 http://jersey.java.net/nonav/apidocs/1.1.0-ea/contribs/jersey-multipart/com/sun/jersey/multipart/file/DefaultMediaTypePredictor.CommonMediaTypes.html

就我而言,我将 PDF 文档发布到另一个站点:

FormDataMultiPart p = new FormDataMultiPart();
p.bodyPart(new FormDataBodyPart(FormDataContentDisposition
        .name("fieldKey").fileName("document.pdf").build(),
        new File("path/to/document.pdf"),
        DefaultMediaTypePredictor.CommonMediaTypes
                .getMediaTypeFromFileName("document.pdf")));

然后 p 作为第二个参数传递给 post()。

这个链接对我把这个代码片段放在一起很有帮助:http: //jersey.576304.n2.nabble.com/Multipart-Post-td4252846.html

于 2012-01-10T13:14:12.913 回答
4

这对我来说很好 url:http ://example.com/rest/muqsith/get-file?filePath=C :\Users\I066807\Desktop\test.xml

@GET
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
@Path("/get-file")
public Response getFile(@Context HttpServletRequest request){
   String filePath = request.getParameter("filePath");
   if(filePath != null && !"".equals(filePath)){
        File file = new File(filePath);
        StreamingOutput stream = null;
        try {
        final InputStream in = new FileInputStream(file);
        stream = new StreamingOutput() {
            public void write(OutputStream out) throws IOException, WebApplicationException {
                try {
                    int read = 0;
                        byte[] bytes = new byte[1024];

                        while ((read = in.read(bytes)) != -1) {
                            out.write(bytes, 0, read);
                        }
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
        return Response.ok(stream).header("content-disposition","attachment; filename = "+file.getName()).build();
        }
    return Response.ok("file path null").build();
}
于 2013-05-16T06:49:51.053 回答
1

另一个示例代码,您可以在其中将文件上传到 REST 服务,REST 服务压缩文件,客户端从服务器下载压缩文件。这是使用 Jersey 使用二进制输入和输出流的一个很好的例子。

https://stackoverflow.com/a/32253028/15789

这个答案是我在另一个帖子中发布的。希望这可以帮助。

于 2015-08-27T15:37:48.673 回答