We are migrating our session based application to REST APIs. In our current application, downloading small excel files dynamically by writing generated excel work book to OutputStream which we get from HttpResponse object. Below is the current code to download excel.
@RequestMapping(value = "exportRules", method = GET)
public void exportRuleResults(final HttpServletRequest request, final HttpServletResponse response)
{
try {
final SXSSFWorkbook workbook = new SXSSFWorkbook(100);
// summary report
final Sheet sheet = workbook.createSheet("Rules Details");
//Headers (First row of report)
final int rows = writeRulesHeaders(workbook, sheet);
int pageNumber = 0;
final ExportReturnVals ret = new ExportReturnVals(1, true);
ret.rowIndex = rows;
ret.totalnumberOfRecords = 1;
while (ret.hasMoreRows) {
writeRows(pageNumber, sheet, ret, workbook);
pageNumber++;
}
OutputStream os=getOutputStream(response, ret);
workbook.write(os);
response.flushBuffer();
workbook.dispose();
os.close();
} catch (final IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
private OutputStream getOutputStream(final HttpServletResponse response, final ExcelExportReturnVals ret) throws IOException {
final OutputStream os = response.getOutputStream();
OutputStream outputStream;
if (ret.totalnumberOfRecords > MAX_RECORD_NONZIP) {
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename="" + "RuleDetails" + ".zip"");
outputStream = new ZipOutputStream(new BufferedOutputStream(os));
((ZipOutputStream) outputStream).putNextEntry(new ZipEntry("RuleDetails" + ".xlsx"));
}else {
response.setContentType("application/xlsx");
response.addHeader("Content-Disposition", "attachment; filename="" + "RuleDetails" + ".xlsx"");
outputStream = new BufferedOutputStream(os);
}
return outputStream;
}
How to achieve this ( without saving file to temporary path and downloading dynamically) using REST API where we can not use HTTP Response object?