繁体   English   中英

Angular:无法下载服务器端生成的电子表格

[英]Angular: can't download server side generated spreadsheet

我正在尝试下载服务器生成的电子表格。

我的应用程序在前端使用Angular,在后端使用Java。

这是后端上接收生成和返回文件请求的方法:

@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)));
}

在前端,当用户单击“下载”按钮时,将执行以下功能:

$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
        });
};

返回的电子表格包含不可读的字符。

如果我直接访问http://127.0.0.1:8000/api/excel/download ,则下载的电子表格不带.xls扩展名(根本没有扩展名)。 如果重命名添加.xls扩展名的文件,然后打开它,则可以看到文件内容。 所以我认为问题出在Angular对后端的调用上,而不是在Java上生成文件。

有没有人遇到过这种情况或可以分享一些例子? 我究竟做错了什么?

Content-Disposition标头应该可以解决问题。 因此,您将获得以下内容:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM