How do you transfer byte[] data using a DTO in Java Spring?

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.

Answer №1

The default behavior in Jackson is to serialize a byte array to base64, meaning you will need to decode it before using.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The speed of Mean Stack API calls leaves much to be desired

Our team has developed a MEAN stack application that functions smoothly on the client side. However, we have been facing issues with slow API requests and responses on the server side. For example, when a request is sent from Angular, it takes an average ...

flushMicrotasks does not function properly in conjunction with the image.onload event

Working on an Angular project, I'm currently developing an object with an image field. The method responsible for loading the image returns a promise that resolves in the onload function of the image. When trying to test this method using the flushMi ...

Manipulating variables across various methods in TypeScript

I have a simple code snippet where two variables are defined in the Main method and I need to access them from another method. However, I am encountering an issue with 'variables are not defined', even though I specified them in the declerations ...

Is it possible to use non-numeric values as keys in a Typescript Map?

During a lesson: private items: Map<number, string> = new Map(); ... this.items[aNumber] = "hello"; Results in this error message: An element has an any type because the expression of type number cannot be used to index type Map<numbe ...

component is receiving an incompatible argument in its props

I am facing a situation where I have a component that works with a list of items, each with an ID, and a filtering function. The generic type for the items includes an ID property that all items share. Specific types of items may have additional properti ...

Upon loading a website, the Chrome browser will automatically set the zoom level to 80%

Recently, I've encountered a perplexing issue with Chrome where my website is automatically zoomed out from 100% to 80%. It seems that browsers cache zoom settings based on the domain and apply them when users revisit the site. However, in this case, ...

Solving the issue of localizing the Datetime picker

My date input seems to be saving incorrectly in the database. When I enter a date like 18/02/2020, it gets saved as 17/02/2020 22:00:00. Is this a time zone issue? How can I fix this problem and thank you. Also, if I want to save the date with UTC, how do ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

Setting up the Font Awesome Pro version in Angular using the Font-Awesome package

The process of installing the pro version of Angular Font-awesome began with setting up my registry using these commands: npm config set "@fortawesome:registry" https://npm.fontawesome.com/ && \ npm config set "//npm.fontawesome.com/:_authTo ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

Utilizing React with Typescript to create JSX text translation files

My task involves translating text stored in a file... ///translations.txt const TEXT: { [x: string]: { [y: string]: string } } = { en: { joinNow: <React.Fragment>Join <b>Now<b/></React.Fragment>, signUp: <React.Fragmen ...

The npm installation process seems to be taking an eternity in this Angular 2 project

Recently, I've been facing a frustrating issue with my Angular 2 project. Whenever I run the npm install command, it seems to be stuck in an endless loop. The progress bar fills up, only for a new npm install command to appear, followed by another pro ...

What is the best way to limit the types of function parameters in TypeScript based on whether the parameter index is even or odd?

My goal is to create a function with an unlimited number of parameters, where the type of each parameter is determined by whether its index is odd or even. For example: flow(isMachineReady(), 'and', isWaterHot(), 'or', isMilkHot(), &ap ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

Having trouble installing Angular 4 with npm?

After installing Angular, I encountered an error when trying to use the command line "ng -v". Please refer to the attached jpeg file. My node version is 6.10.3. Does anyone have a solution? ...

An issue (TC2322) has been encountered during the compilation of the Angular4 application

Encountered an issue while running the "ng build" command: ERROR in src/app/model/rest.datasource.ts(34,5): error TS2322: Type 'Observable<Product | Order | Product[] | Order[]>' is not assignable to type 'Observable<Product[]>& ...

Excluding a common attribute from a combined type of objects can lead to issues when accessing non-common attributes (TypeScript)

In the process of developing a wrapper function, I am passing a refs property into a send function. The Event type used to construct my state machine is defined as an intersection between a base interface { refs: NodeRefs } and a union of possible event ob ...

What is the reason that control flow analysis does not support the never type?

Here is the scenario I'm dealing with (utilizing strictNullChecks): function neverReturns(): never { throw new Error(); } const maybeString: string | null = Math.random() > 0.5 ? "hi" : null; if (!maybeString) { neverReturns(); // th ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...