从Spring Rest API下载文件

时间:2019-07-05 18:39:10

标签: javascript java file spring-boot download

我跟随spring控制器下载了一个文件,当我直接调用端点并获得带有加密内容的csv文件时,该文件运行良好。

@GetMapping(value = "registered-cards")
    public ResponseEntity<byte[]> generateRegisteredCards(@RequestParam("from") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime from,
                                                               @RequestParam("to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime to) throws Exception {

        byte[] bytes = cfsbReportingService.generateRegisteredCardsReport(from, to);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + "report-" +  LocalDateTime.now() + ".csv");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

我在JavaScript上有以下代码来调用端点并下载文件。问题是我可以下载文件,但不能解密,而直接调用端点下载文件时,文件就会被解密。

public getRegisteredCards(fromDate, toDate) : void {
        const fromEst = fromDate.startOf('day').tz('America/New_York').format();
        const endEst = toDate.endOf('day').tz('America/New_York').format();
        this.reportingService.generateNewRegisteredCardsFile(fromEst, endEst).then(
            (response:any) => {
                const blob = new Blob([response.data], {type:  'application/octet-stream'});
                const hiddenElement = document.createElement('a');
                hiddenElement.href = window.URL.createObjectURL(blob);
                hiddenElement.target = '_blank';
                hiddenElement.download = 'file.csv';
                hiddenElement.click();
            }
        ).catch(this.handleError(''));

呼叫服务器:

public generateNewRegisteredCardsFile(from: String, to: String) {
        const url = `${this.api()}/reporting/v1/registered-cards?from=${from}&to=${to}` ;
        const headers = new Headers({'Content-Type': 'application/octet-stream', 'Accept': 'application/octet-stream', 'Access-Control-Allow-Origin': '*'});
        return this.$http.get(url, headers);
    }        }

我在这里做错了什么?我看了几十个例子,这就是文件的下载方式。

谢谢!

1 个答案:

答案 0 :(得分:0)

我最终添加了如下所示的DTO对象,并如下更改了我的rest控制器:

@Data
public class RegisteredCardsReport {

    public RegisteredCardsReport(byte[] encryptedReport, String fileName) {
        this.encryptedReport = encryptedReport;
        this.fileName = fileName;
    }

    byte[] encryptedReport;
    String fileName;
}

//剩余端点更改

@GetMapping(value = "new-registered-cards")
    public ResponseEntity<RegisteredCardsReport> generateNewRegisteredCards(@RequestParam("from") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime from,
                                                                                    @RequestParam("to") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) ZonedDateTime to) {

        byte[] encryptedRpt = ReportingService.generateRegisteredCardsReport(from, to);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Access-Control-Allow-Origin", "*");
        RegisteredCardsReport cardsReport = new RegisteredCardsReport(encryptedRpt, "registered-cards--" + LocalDateTime.now() + ".csv");
        return new ResponseEntity<>(cardsReport, headers, HttpStatus.OK);
    }

,最后使用本文中接受的答案来创建文件: Download File from Bytes in JavaScript