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

Angular - The element contains an implicit 'any' type due to the absence of an index signature in the 'AbstractControl' type

Within my Angular-11 project, I am utilizing the following TypeScript code: multistep = new FormGroup({ userDetails: new FormGroup({ first_name: new FormControl(''), last_name: new FormControl(''), other_na ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

What is the best way to merge two interfaces and convert all of their fields to optional properties?

I have two unalterable interfaces: interface Person { name: string; age: number; } interface User { username: string; password: string; } I aim to merge them into a single interface called Player // please, adjust this code accordingly interfac ...

Typing Redux Thunk with middleware in TypeScript: A comprehensive guide

I recently integrated Redux into my SPFx webpart (using TypeScript), and everything seems to be working fine. However, I'm struggling with typing the thunk functions and could use some guidance on how to properly type them. Here's an example of ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Problem with extending a legacy JavaScript library using TypeScript

Can someone assist me with importing files? I am currently utilizing @types/leaflet which defines a specific type. export namespace Icon { interface DefaultIconOptions extends BaseIconOptions { imagePath?: string; } class Default exte ...

Custom typings for Next-Auth profile

I'm experiencing an issue with TypeScript and Next Auth type definitions. I followed the documentation guidelines to add my custom types to the NextAuth modules, specifically for the Profile interface in the next-auth.d.ts file. It successfully adds t ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Building a Docker image encounters an issue during the npm install process

Trying to utilize Docker with an Angular application, encountering issues during npm install within the Docker build process. When running npm install locally, no dependency errors or warnings occur. Error log from docker build: > [node 4/6] RUN npm i ...

Instruct the main component to retrieve updated information

Within my parent component, there is a router outlet containing a component that generates new objects associated with the parent. I'm unsure how to notify the parent component to make a new API call for updated data. Can you assist me in understandin ...

Tips for arranging various information into a unified column within an Antd Table

Is there a way to display multiple data elements in a single cell of an Ant Design table, as it currently only allows insertion of one data element? I am attempting to combine both the 'transactionType' and 'sourceNo' into a single cell ...

Utilizing Functions in Next.js with TypeScript: A Guide to Reusability

It is considered a best practice to separate data fetching functions into a folder named services, but I'm having trouble implementing this in my Next.js project. The function works when placed inside the component where I want to render the data, but ...

When attempting to change a Component's name from a string to its Component type in Angular 9, an error is thrown stating that the passed-in type is

When working with Template HTML: <ng-container *ngComponentOutlet="getComponent(item.component); injector: dynamicComponentInjector"> </ng-container> In the .ts file (THIS WORKS) getComponent(component){ return component; //compo ...

The system does not acknowledge 'NODE_OPTIONS' as a command that can be used internally or externally, or as an operational program or batch file

While trying to build my react + vite project, I encountered an error after running npm run build. https://i.stack.imgur.com/XfeBe.png Here is a snapshot of my package.json file. https://i.stack.imgur.com/MbbmY.png ...

Troubleshooting the issue with mocking the useTranslation function for i18n in JEST

Currently, I am facing an issue with my react component that utilizes translations from i18next. Despite trying to create tests for it using JEST, nothing seems to be getting translated. I attempted to mock the useTranslation function as shown below: cons ...

Loop through an array using NgFor directive in Angular

I am facing a challenge where I have an object in my front-end application that needs to be iterated over using ngFor. The response received from the backend is structured as follows: @Component({ selector: 'docker-logs', templateUrl: ' ...

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

What is the best way to eliminate the final character in an input value once it has passed through regex validation in Angular8

Hello! I am attempting to remove the last digit of a string and update the input value each time my function checks if the input value passes a regex test on keypress. Initially, it works correctly, but then it adds an extra digit. After that, it works a ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

Filtering Deno tests by filename: A step-by-step guide

How can I selectively run Deno tests based on their filenames? Consider the following test files: number_1_test.ts number_2_test.ts string_test.ts If I want to only run tests with filenames starting with number*, I am unable to use either of these comma ...