我正在尝试找到一种无需 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 返回作为后端的响应,然后使用 file-saver下载文件
this.http.get(`/api/applications/export`, params, { responseType: 'blob' })
.subscribe((resp: any) => {
saveAs(resp, `filename}.xlsx`)
});
关于java - 从rest api下载文件而不需要window.open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473686/