Input and Output binary streams using JERSEY?
I managed to get a ZIP file or a PDF file by extending the StreamingOutput
object. Here is some sample 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 { PDFGenerator generator = new PDFGenerator(getEntity()); generator.generatePDF(output); } catch (Exception e) { throw new WebApplicationException(e); } } };}
The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.
Don't know if it's the best way to do it, but it works.
I had to return a rtf file and this worked for me.
// create a byte array of the file in correct formatbyte[] docStream = createDoc(fragments); return Response .ok(docStream, MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition","attachment; filename = doc.rtf") .build();
I'm using this code to export excel (xlsx) file ( Apache Poi ) in jersey as an attachement.
@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();}