![](/img/trans.png)
[英]Download generated PDF use FileSaver on client side and Snappy on server side
[英]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.