java - 从没有window.open的rest api下载文件
问题描述
我正在尝试找到一种无需 window.open() 从 api 下载文件的方法。我想在调用 api 时立即下载。
目前正在使用 window.open() 下载由 rest api 生成的 .xls 文件
API端点
@GetMapping("/applications/export")
@Timed
public ResponseEntity<byte[]> exportApplicationsList() {
log.debug("REST request to export applications list");
byte[] result = applicationService.generateApplicationsListAsExcel();
if (result == null) {
return ResponseEntity.status(500).build();
}
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd_MM_yyyy_HH_mm"));
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=liste_applications_" + date + ".xls")
.contentLength(result.length)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(result);
}
服务
/**
* Generate xls file from applications list.
*
* @param applications list of applications
*/
public byte[] generateApplicationsListAsExcel() {
log.info("Génération fichier xls de la liste des applications");
List<Application> applications = applicationRepository.findAll();
Collections.sort(applications);
try (InputStream is = new FileInputStream(ResourceUtils.getFile("classpath:jxls-templates/liste_applications_template.xls"))) {
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
Context context = new Context();
context.putVar("applications", applications);
JxlsHelper.getInstance().processTemplate(is, os, context);
return os.toByteArray();
} catch (IOException e) {
log.error(e.toString());
}
} catch (IOException e) {
log.error(e.toString());
}
return null;
}
调用
exportApplicationsList(): void {
window.open('/api/applications/export');
}
解决方案
您可以将文件作为blob作为后端的响应返回,然后使用文件保护程序下载文件
this.http.get(`/api/applications/export`, params, { responseType: 'blob' })
.subscribe((resp: any) => {
saveAs(resp, `filename}.xlsx`)
});
推荐阅读
- c# - MySqlConnection 抛出 3 个异常,都调用它的 Open() 方法
- python - 使用 Pandas 整理/整理数据(电话号码)
- c++ - c 此代码控制语句如何工作
- android - Android - 管理布局景观
- c - ntohs() 可以应用于 uint8_t
- tibco - 如何删除队列和桥接队列
- javascript - javascript 正则表达式匹配单个或范围
- python - 将数据集中的某些单元格与python中的标量相乘
- reactjs - React 中的 Google Map API:如何为每个标记分配 InfoWindow
- javascript - 在 ECMAScript 规范中,我们可以准确地找到新词法环境的创建时间?