I am currently facing an issue with my server-side application. The problem arises when attempting to convert a Blob to an Excel file on the front-end, specifically when the byte[] is sent within a DTO.
When sending a POST request from the back-end (spring), if I send byte[] directly, it arrives correctly on the front-end (angular, typescript). However, if I send byte[] within a DTO object, the conversion process goes wrong and I'm unable to understand why. By "going wrong", I mean that when trying to create an Excel file from the byte[] (which is a Blob in typescript), it fails - the resulting Excel file cannot be opened. Furthermore, upon inspecting the file in a text editor (e.g. notepad++), I can see strange bytes characters like "UEsDBBQACAgIAC2oPVQAAAAAAAAAAAA" which is incorrect as a normal Excel file should be displayed differently.
Below is the code for both scenarios:
1. Working Variant without DTO
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'});
}
This variant produces a correctly functioning Excel file that can be opened with MS Excel and appears fine even when viewed in a text editor.
2. Problematic Variant with DTO (non-working)
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);
}
In this scenario, the resulting Excel file cannot be opened with MS Excel and displays strange characters in a text editor.
The issue seems to lie in the file generation process itself rather than the saving part.