Reputation: 4881
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);
}
Upvotes: 1
Views: 4184
Reputation: 4881
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 });
});
}
Upvotes: 3