0

I'm trying to download a server generated spreadsheet.

My application uses Angular on the front-end and Java on the back-end.

Here's the method on the back-end that receives the request to generate and return the file:

@RequestMapping(value = "download", method = RequestMethod.GET, produces = "application/xls")
public ResponseEntity<InputStreamResource> download() throws IOException {
    ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet worksheet = workbook.createSheet("POI Worksheet");

    HSSFRow row1 = worksheet.createRow((short) 0);

    HSSFCell cellA1 = row1.createCell((short) 0);
    cellA1.setCellValue("Hello!");
    HSSFCellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    cellA1.setCellStyle(cellStyle);

    workbook.write(fileOut);
    fileOut.close();

    byte[] file = fileOut.toByteArray();

    return ResponseEntity
            .ok()
            .contentLength(file.length)
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new InputStreamResource(new ByteArrayInputStream(file)));
}

And on the front-end, the following function is executed when the user clicks on Download button:

$scope.exportFile = function() {
    $http.get('http://127.0.0.1:8000/api/excel/download')
        .success(function (data, status, headers, config) {
            var anchor = angular.element('<a/>');
            anchor.attr({
                href: 'data:application/octet-stream;charset=utf-8,' + encodeURI(data),
                target: '_blank',
                download: 'spreadsheet.xls'
            })[0].click();
        })
        .error(function (data, status, headers, config) {
            // handle error
        });
};

The returned spreadsheet contains unreadable characters.

If I access http://127.0.0.1:8000/api/excel/download directly, the spreadsheet is downloaded without the .xls extension (with no extension at all). If I rename the file adding the .xls extension and then open it, I can see the file contents. So I think the problem it's on the call Angular does to back-end and not on generating the file on Java.

Has anyone experienced this situation or have some example to share? What am I doing wrong?

Marcos Tanaka
  • 3,112
  • 3
  • 25
  • 41

1 Answers1

0

The Content-Disposition header should do the trick. So, you would have something like this:

HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("Attachment", "spreadsheet.xls");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(file.length);

return new ResponseEntity<InputStreamResource>(
           new InputStreamResource(new ByteArrayInputStream(file)),
           headers, HttpStatus.OK);
Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359