I work for a server-side application and I have a problem: on front-end, a Blob ins't converted properly to Excel file if the byte[] is sended within a dto
For a POST request, from back-end(spring) if I send byte[], it arrived well in front-end (angular, typescript), but if I send byte[] within a DTO object, it become wrong and I don't understand why. The meaning of "become wrong": if I try to create a Excel file from byte[] (which is Blob in typescript) this won't work - the resulting excel file cannot be opened, and if I try to open it with a text editor (e.g notedpad ) I see that there are bytes characters (e.g "UEsDBBQACAgIAC2oPVQAAAAAAAAAAAA" and so on) which is wrong, because a normal Excel file is seen in a different way with a text editor.
Now the code:
1. The variant without DTO (this works)
Java:
@PostMapping("/exportData")
@Transactional
public byte[] exportData(@RequestBody ExportRequestDTO exportRequestDTO){
// other stuff
byte[] a = new byte[5];
return a;
}
Typescript:
requestFileForExport(exportRequestDTO : ExportRequestDTO):Observable<HttpResponse<Blob>>{
return this.httpClient.post(`${this.exportDataURL}`,exportRequestDTO, {responseType: 'blob',observe: 'response'});
}
And:
this.exportDataService.requestFileForExport(exportRequestDTO).subscribe((data:HttpResponse<Blob>)=>{
let blob = new Blob([data.body], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
saveAs(blob,"file.xlsx");
});
I can open resulting excel file (with MS Excel) and looks fine. This is how it looks if I open with a text editor:
2 .The variant with DTO (which create a wrong excel file - so this variant don't work. WHY?)
Java:
public class FileDTO {
private byte bytes[];
private String fileName;
// constructors, getters and setters
}
And:
@PostMapping("/exportData")
@Transactional
public FileDTO exportData(@RequestBody ExportRequestDTO exportRequestDTO){
FileDTO a = new FileDTO();
// other stuff
return a;
}
Typescript:
export class FileDTO {
bytes:Blob;
fileName:string;
constructor(bytes: Blob, fileName: string) {
this.bytes = bytes;
this.fileName = fileName;
}
}
And:
requestFileForExport(exportRequestDTO : ExportRequestDTO):Observable<FileDTO>{
return this.httpClient.post(`${this.exportDataURL}`,exportRequestDTO);
}
And:
this.exportDataService.requestFileForExport(exportRequestDTO).subscribe(data=>{
let res = data;
let blob = new Blob([res.bytes], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
saveAs(blob,"file.xlsx");
});
I can't open resulting excel file with MS Excel. Also, this is how it looks if I open with a text editor

saveAs is from file-saver js, but the result is the same (variant 1 works, variant 2 not) if I tried to do a manual file save - the problem is file itself, not save part
CodePudding user response:
Jackson serializes byte array to base64 by default, so you will have to decode it first..
