具有自定义名称的导出文件

问题描述 投票:0回答:1

我想实现此代码示例,该示例用于从Spring BE导出数据。

@GetMapping("export/{ids}")
    public void export(HttpServletResponse response, @PathVariable List<Integer> ids) {

        List<Transactions> transactions = (List<Transactions>) transactionService.findAll(ids);
        List<TransactionExcelEntry> entries = transactions.stream().map(payment_transaction_mapper::toExcel).collect(Collectors.toList());

        List<String> headers = Arrays.asList("Id", "Name", "Type", "Created at");
        try {
            response.addHeader("Content-disposition", "attachment; filename=Transactions.xlsx");
            response.setContentType("application/vnd.ms-excel");
            new SimpleExporter().gridExport(headers, entries, "id, name", response.getOutputStream());
            response.flushBuffer();

        } catch (IOException ex) {
            LOG.debug("parsing of transactions failed");
        }
    }

导出按钮:

<button class="dropdown-item" (click)="export()">XLS</button>

导出功能:

export() {
    var newPagination = new Pagination();
    newPagination.size = this.pagination.size * this.pagination.total
    this.transactionService.search(newPagination, this.formGroup.value)
        .subscribe(result => {
            this.formGroup.enable();
            const query = result.content.map(t => t.id).join(',');
            this.transactionService.exportRows(query).subscribe(data => {
                const a = document.createElement('a');

                a.href = window.URL.createObjectURL(data);
                a.download = 'export.xls';
                a.click();
            });
        }, (error) => {
            this.formGroup.enable();
        });
  }

exportRows(query) {
    return this.http.get(`/api/transactions/export`, { responseType: 'blob' });
}

我想将文件名生成到Java BE中,然后从Angular FE中下载它。如何实现此功能?

angular spring angular7 angular8
1个回答
0
投票

因此,如果您想自己构建文件,则FE基本上需要读取Content-disposition标头。据我所知,后端需要向Access-Control-Expose-Headers添加Content-disposition标头,然后在observe: 'response'中添加get参数时,Angular可以通过其HttpClient读取它: >

return this.http.get(`/api/transactions/export`, { responseType: 'blob', observe: 'response' });

但是,如果您要的是Blob,我认为您不能使用它来构建所需的文件,因为它是不可变的。所以我可能会在get中使用ArrayBuffer:

 return this.http.get(`/api/transactions/export`, { responseType: 'arraybuffer', observe: 'response' });

(AFAIK也有FileReader的readAsArrayBuffer(),可从Blob转换。

然后您可以在subscribe中进行检查,并且应该有带有文件名和正文的标头。

© www.soinside.com 2019 - 2024. All rights reserved.