首页 > 解决方案 > 从没有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');
    }

标签: javaangulartypescriptrest

解决方案


您可以将文件作为blob作为后端的响应返回,然后使用文件保护程序下载文件

this.http.get(`/api/applications/export`, params, { responseType: 'blob' })
  .subscribe((resp: any) => {
    saveAs(resp, `filename}.xlsx`)
});

推荐阅读