1

I am using file saver on Angular 7 to save CSV file returned from Spring Boot backend. Spring Boot returns CSV File object with some properties i.e name, size, type, and file content in a byte array format. When I open save page, File Saver saving file with byte array text instead of converting to CSV format and saving it to the file.

getFileContent

getFileContent(id)
  {
    this.filesService.getFileContent(SERVER_API_URL + "files/" + id).subscribe(
      data =>
      {
        this.fileObservable = data;
        let blob = new Blob([this.fileObservable.fileContent], {type: "text/csv;charset=utf-8"});
        saveAs(blob, "test.csv",{ autoBOM: true });
      });
  }

Rest API:

@GetMapping(value = "/files/{id}")
    public CsvFile getFileById(@PathVariable Long id)
    {
        return csvUploadService.getFileById(id);
    }
1
  • I think Angular 7 converting byte input to Base64 format. Does anyone know how to prevent this? Commented Jan 22, 2019 at 18:31

1 Answer 1

3

Part of the issue was with Base64 conversion by Angular. When byte[] data received from Spring, Angular converting it to Base64 string. I used blob-util to convert Base64 string to byte[] and then passed it to File-Saver. Updated code as follows

getFileContent

 getFileContent(id)
  {
    this.filesService.getFileContent(SERVER_API_URL + "files/" + id).subscribe(
      data =>
      {
        this.fileObservable = data;
        let contentType='text/csv';
        let blob = base64StringToBlob(this.fileObservable.fileContent, contentType);
        saveAs(blob, "test.csv",{ autoBOM: true });
      });
  }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I was having trouble with something similar and this solved my issue, I owe you a beer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.