简体   繁体   中英

Downloading a file from spring rest api

I have following spring controller to download a file which is working fine when I directly call the endpoint and I get a csv file with encrypted content .

@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);
    }

I have following code on my javascript to call the endpoint and download the file. The thing is I can download the file but I cannot decrypt it whereas when I download the file by directly calling the endpoint, it gets decrypted.

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(''));

Call to server:

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);
    }        }

What am I doing wrong here? I looked at tens of examples and that's how file gets downloaded.

Thank you!

I ended up adding a DTO object like below and changed my rest controller as follows:

@Data
public class RegisteredCardsReport {

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

    byte[] encryptedReport;
    String fileName;
}

//Rest Endpoint change

@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);
    }

and finally used the accepted answer in this post to create file: Download File from Bytes in JavaScript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM