"Encountered a problem while attempting to download the .xlsx file through http.get in an angular application interfacing

Attempting to download a .xlsx file using Angular 7 and web API in C#, encountering the following error:

https://i.sstatic.net/7pwDl.png

The code snippet from my service.ts is provided below:

public exportExcelFile(matchedRows: string, reportInfoId: number): Observable<any> {
        const httpOptions = {
            headers: new HttpHeaders({ 'responseType':  'ResponseContentType.Blob',
            'Content-Type':  'application/vnd.ms-excel'})};
        const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;

        return this.http.get(url, httpOptions);

    }

The method that utilizes my service:

exportExcelFile(matchedRows:string){
        this.service.exportExcelFile(matchedRows, this.reportInfo.ide).subscribe((response)=>{
            console.log(response)
        })  
        this.exportingExcelFile=false;
        this.ready=true;
    }

The method responsible for retrieving response from the API:

[HttpGet]
public IHttpActionResult ExportExcelFile(int reportId, bool matchedRows)
{

    var user = Request.GetAuthenticatedUser();
    var query = new GetExcelFileQuery(reportId, user.UserName, matchedRows);
    var result = _dispatcher.Dispatch<GetExcelFileQuery, GetExcelFileModel>(query);

    using (var memoryStream = new MemoryStream()) //creating memoryStream
    {
        result.Workbook.Write(memoryStream);

        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new ByteArrayContent(memoryStream.ToArray());
        response.Content.Headers.ContentType = new MediaTypeHeaderValue
               ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.Content.Headers.ContentDisposition =
               new ContentDispositionHeaderValue("attachment")
               {
                   FileName = result.FileName
               };

        return result == null ? NotFound() : (IHttpActionResult)new FileResult(response);
    }
}

If accessing the URL directly through the browser, the excel file exports correctly.

Answer №1

It appears that your backend is functioning correctly. However, the issue lies with the client attempting to interpret the response as a JSON file. 'responseType' should be simply set to 'blob' and placed outside of the HttpHeaders object. In this case, you can remove the httpHeaders object entirely.

const url = `${environment.apiUrl}report/${reportInfoId}/exportExcelFile?matchedRows=${matchedRows}`;
return this.http.get(url, {responseType: 'blob'});

For more information on the responseType object, please refer to: https://angular.io/api/common/http/HttpRequest#responseType

Answer №2

Service.ts

   public createExcelReport(matchedRows: string, reportInfoId: number): Observable<any> {

        const url = `${environment.apiUrl}report/${reportInfoId}/generateExcelFile?matchedRows=${matchedRows}`;

        return this.http.get(url,{  observe: 'response', responseType: 'blob'} );

    }

Method that invokes the service

createExcelReport(matchedRows:string){
        this.service.createExcelReport(matchedRows, this.reportInfo.ide).subscribe((response)=>{

            const blob = new Blob([response.body],
                { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            const file = new File([blob], 'reports.txt',
                { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });


            saveAs(file);
        })  

using

import { saveAs } from 'file-saver';

The Excel file is successfully generated

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

Guide on deploying an Angular application with SSL support

I feel a bit lost on this matter, but I'm working on hosting my angular website on github pages with a custom domain name. My goal is to enable https for added security, but I can't quite figure out the process. Do I need to include more code to ...

Unable to generate Angular project using the command "ng new app_name" due to error code -4058

Whenever I try to run the command ng new app-name, I encounter error -4058. If I execute the same command while opening cmd as an administrator in the directory C:/Windows/system32, the project creation process goes smoothly. However, if I change the dire ...

Bizarre npm setup

I'm new to Node and struggling with upgrading my package to enable web workers. I'm attempting to move from Angular 6.x.x to 7.x.x and then to 8.x.x. However, every time I try to install updates, it initially seems like it's successful but e ...

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

Set values to the inner property of the object

In my configuration file, I have set up nested properties as shown below export class Config { public msalConfig: { auth: { authority: string; clientId: string; validateAuthority: boolean; redirectUri: ...

NextJS and Context API throwing a Typescript error

I've been working on my _app.tsx file and here's the code snippet I have: import React from 'react' import type { AppProps } from 'next/app' /* Import Styles */ import '@themes/index.scss' /* Import Template */ imp ...

Can a TypeScript file be created by combining a declaration file and a .js file?

It is commonly understood that declaration files are typically used for libraries rather than projects. However, let's consider a scenario where an existing JavaScript project needs to be migrated to TypeScript by creating d.ts files for each source ...

I encountered a challenge while developing an ASP.NET application with CRUD functionality - I found that I was unable to add new products due to the ModelState.IsValid

My ASP.NET MVC web app with CRUD functionalities is causing an issue where ModelState.IsValid always returns false upon clicking the create button. Upon debugging, I discovered that the dropdown for selecting a category from another table (which serves as ...

Even after installing npm3, the npm -v command continues to display version 2.x.x

As I delve into the world of Angular 2, I learned that it requires npm version 3.x.x. Despite installing npm3 with the command npm install -g npm3, when I check my npm version using npm -v, it still shows as 2.15.8. Strangely, running npm3 -v displays vers ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

What could be causing me to consistently receive a 0 value despite my collection having content stored within it?

How can I retrieve the value of dropVolume and use it in another method after executing my getAllDropsVolumePerDate(date) function? Each time I try to access dropVolume, it returns a value of 0. dropVolume = 0; getAllDropsVolumePerDate(date: string) { ...

Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students. import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm" /* * Adhering to ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

Using the typescript infer feature does not function properly when dealing with arrays

My TypeScript code is causing some unexpected results: const myObject = { foo: ['a', 'b', 'c'] } type MyType = typeof myObject.foo extends [...infer Content] ? string : boolean The type MyType is coming out as 'string ...

Is it possible to integrate Angular-cli with babel transforms?

My current project is a unique combination of AngularJS and Angular, with Gulp handling the transformations for the Angular portion. We are converting TS to ES6, then using Babel to transpile to ES5+ before utilizing Rollup or SystemJS. There's a lot ...

Using TypeScript with Vue allows you to customize the default export of Vue

Currently experimenting with Vue and TypeScript, attempting to compile to AMD in my tsconfig file. The type definition in vue/types/index.d.ts for Vue.js includes: export default Vue; However, this results in TypeScript compiling it like this: import V ...

Is it possible to utilize Selenium WebDriver for automation with C# in Visual Studio 2010?

Is it possible to utilize Selenium WebDriver for automation with C# in Visual Studio 2010? I am currently working on automating a series of processes with a set algorithm. After researching my options, I believe Selenium WebDriver would be a good fi ...

What is the best method for positioning two forms in a vertical arrangement?

I'm looking to integrate a Login form in HTML within my C# project. Here's what I have so far: However, as you can see, the layout is not very aesthetically pleasing. I'm struggling to align the elements in a more visually appealing way. My ...

Managing optgroup in select dropdown using Angular 4

Is there a way to retrieve the optgroup label value within an onchange function on a select box in Angular 4? In my form, I have a select box with multiple dates as option groups and time slots in 24-hour format for booking (e.g. 1000 for 10AM, 1200 for 1 ...