Sending binary information from a .net core web api to a typescript application

I currently have a .net core 3.0 web api application connected to an angular 8 client. While I have successfully transferred data between them using json serialization, I am now looking for a way to transfer a bytes array from the api to the client.

After some research, I discovered that the recommended method to send binary data is through IActionResult instead of HttpResponseMessage. In my controller, I implemented the following code:

       [HttpGet("Get-octetstream/{id}")]
       public async Task<FileResult> GetAsOctetStream(int id)
       {
           var bytes= await GetData(id);
           var stream = new MemoryStream(bytes);
           return File(stream, "application/octet-stream", $"{id}.bin");
       }

Upon testing, it worked perfectly fine as the data was saved in a file when accessed directly from the browser. The content was also correct.

However, when attempting to request this data from the Angular application:

    async getOctetStreamFromServer(id: number) {
    const url =
      Utils.GetWebApiUrl() + `/misc/Get-octetstream/${id}`;
    const currentUser = JSON.parse(sessionStorage.currentUser);

    const myHttpOptions = {
      headers: {
        Authorization: "Bearer " + currentUser.jsonWebToken,
        ResponseType: "blob",
      },
    };

    const response = await this.httpClient.get(url, myHttpOptions).toPromise();
    return response;
  }

An error occurs:

ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":
{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"http://localhost:11080/misc/
Get-octetstream/16588","ok":false,"name":"HttpErrorResponse","message":"Http failure during 
parsing for http://localhost:11080/misc/Get-vxsor-octetstream/16588","error":{"error":
{},"text":"\u0011\u0...

I am seeking guidance on how to fetch binary data from a .NET Core web API service using TypeScript. Any assistance with providing a TypeScript code snippet would be greatly appreciated.

Answer №1

Kindly make necessary adjustments to your choices:

const updatedHttpOptions = {
    headers: {
        Authorization: "Bearer " + currentUser.jsonWebToken,
    },
    responseType: 'arrayBuffer'
};

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

Managing the lifecycles of extended class instances in Angular 2 - what's the best approach?

The code snippet below is causing an issue for me in Angular 2.4.9: export class MyComponent extends BaseComponent implements OnInit { type = 2; constructor() { super(); } ngOnInit(){ console.log('inited type', this.type) } } ...

Can TypeScript automatically deduce keys from a changing object structure?

My goal here is to implement intellisense/autocomplete for an object created from an array, similar to an Action Creator for Redux. The array consists of strings (string[]) that can be transformed into an object with a specific shape { [string]: string }. ...

Understanding the Union Type in Typescript and Its Application in Angular Development

I came across this piece of code: interface Course { code: string; name: string; user: number | { id: number; name: string; }; } This indicates that a course object can contain either the user object or the user key. When fetching the cour ...

What is the best way to access an optional field in Typescript without causing errors?

Is there a way to dereference an optional field from an interface in the following scenario? interface Sample { key1?: Array<Obj1> } interface Obj1 { a?: Obj2; } interface Obj2 { b?: string; } const a: Sample["key1"][number][" ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

JSON.stringify omits any properties in a custom class that have not been explicitly declared in the constructor

I recently defined a new class in my code: export class SavedData{ public isDone : boolean; } After trying to stringify an instance of this class, I noticed that the isDone property was not included: console.log(new SavedData()); This resulted in a ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

Compilation issues encountered while running TypeScript in Dockerfile

I am encountering an issue with my Dockerfile during the TypeScript compilation step. Below is the snippet of code where it fails: FROM node:12 WORKDIR /usr/src/app # SETUP COPY package.json . COPY tsconfig.json . COPY src . RUN npm install -g yarn@^1. ...

What is the reason behind the use of the ";" instead of "&" for passing query parameters in Angular8 routers?

Is there a way to implement route navigation using router.navigate similar to this example? this.router.navigateByUrl(`enrollment?id=${student.id}&request=${"delete"}`); I attempted using this.router.navigate(['enrollment',{id:student.id}]) ...

Identifying Data Types in Typescript Using a Union Type Guard

I came across this interesting type guard: enum X { A = "1" } const isNullableX = (value: any): value is X | null => false let bar: string | null = '' if (isNullableX(bar)) { console.log(bar) } Surprisingly, in the last con ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Renew expired JWT tokens using Angular 11 interceptor in conjunction with a Spring Boot backend

I have been working on a project using spring boot and angular, where users log in from the Angular frontend to the authentication API on Spring Boot to receive a JWT token. To ensure that all requests include this token, I have implemented an interceptor ...

Combining a JSON object with a dropdown menu within an Ionic 3 Angular 4 application

I've hit a roadblock while attempting to integrate a JSON response into an ion-option tag in my HTML code: <ion-item> <ion-label>Country</ion-label> <ion-select formControlName="country"> ...

How can I ensure my variable in Angular 2 waits asynchronously for values to be assigned?

I encountered the following error: TypeError: Cannot read property 'length' of undefined at PaginationComponent.ngOnChanges (pagination.component.ts:38) This is how my PaginationComponent is set up: @Input() items = []; @Input('page-siz ...

Is it possible to make my Toggle/Click event refresh the entire component every time it is clicked?

I'm trying to implement a toggle function to show/hide a specific DIV and dynamically change the button text based on the current state in React Hooks. However, every time I click on it, the entire page seems to re-render in Next.js. I'm not enti ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Differentiating body classes in Angular 5

I am working on a project with both a login screen and a dashboard screen. The body classes for these screens are different, as shown below: <body class="hold-transition skin-black-light sidebar-mini" > // for dashboard <body class="hold-transi ...

Tips for utilizing array.items in joiful validation?

Can someone provide an example code or a link on how to correctly use the joyful validation for array items? I attempted the array.items validation code using joyful, but I am not sure how to specify the items. Thanks in advance! ...

Is there a way to retrieve a particular object from a versatile function?

Here is a generic function to consider: public getData<T>(url: string): Observable<T> { return this.httpClient.get<T>(url); } I am looking for a way to test this function by returning a mock object array, especially if the remote ...

Best practices for configuring a gulpfile.ts

I have configured a gulpfile.ts for my project based on this example from GitHub found here. (I won't be sharing my exact gulpfile.ts as it is similar, just slightly more complex) Every time I run a gulp task, I encounter these 4 errors: [11:53:23] ...