java - 从rest api下载文件而不需要window.open

标签 java angular typescript rest

我正在尝试找到一种无需 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/

相关文章:

java - 如何更新选项卡中的 ListView ?

angular - ViewChildren 找不到动态组件

javascript - 使用 .getElementsByClassName() 的 Angular 2 通过存在返回空选择

angularjs - Chrome 开发工具未映射 ts 源

java - AndroidLauncher 找不到 Assets ,但 DesktopLauncher 可以

java - 使用 Streams 将列表对象复制到另一个具有修改内容的列表对象

java - 另一个 "Can only iterate over an array or an instance of java.lang.Iterable"问题

angularjs - 如何在 Angular 混合应用程序中的组件之间进行通信?

angular - HttpTestingController ExpectOne 仅验证 api 端点

javascript - 在 json_to_sheet 之后使用 XLSX js 对列进行排序和过滤