Angular - Retrieve Excel file with its current filename

Is there a way for me to save an Excel file with its original filename from a service in my Angular app using the file-saver library? Below is my current code:

let blob = new Blob([response],  {type: 'application/vnd.openxmlformat-officedocument.spreadsheetml.sheet;'});
saveAs(blob, 'hello.xlsx');

This is how the response looks like from the Angular service:

return this.http.get(`${this.reportsUrl}`, { responseType: 'blob'});

Here is the response from my backend service (Spring MVC). The excelCreateResource is of type

org.springframework.core.io.Resource
:

return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + excelCreateResource.getFilename() + "\"")
                .body(excelCreateResource);

I want to download the file with its original filename without specifying hello.xlsx. When accessing the URL directly from the browser, I am able to download the Excel file successfully.

Answer №1

If you want to extract header details from a complete response in Angular, you can achieve this by observing the response thoroughly. Utilize the following code snippet:

let response$ = this.http.get(`${this.reportsUrl}`, { observe: 'response'});
response$.subscribe(response => {
  let data = response.body; // This data will be your blob object (the body of the response)
  let headers = response.Headers // The headers can be found in this dictionary or HashMap

//.....

})  

Answer №2

Should the function

excelCreateResource.getFilename();
provide a filename as output, you have the option to save this filename in a local variable and then use it as an argument in the saveAs() method, as demonstrated below:

var fileTitle = excelCreateResource.getFilename();
saveAs(blob, fileTitle);

This approach may be successful for your situation.

Answer №3

Utilizing the FileSaverJs library

let excelOutput = <write output> // write table or json to excel
function stringToArrayBuffer(s) {
  var buffer = new ArrayBuffer(s.length);
  var view = new Uint8Array(buffer);
  for (var i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xFF;
  }
  return buffer;
}
// Save the file as test.xlsx
saveAs(new Blob([stringToArrayBuffer(excelOutput)], {type: "application/octet-stream"}), 'hello.xlsx');

Answer №4

One way to save a File constructor is by not specifying a filename, as the File itself already has a name.

let content = new Blob([data],  {type: 'application/vnd.openxmlformatofficedocument.spreadsheetml.sheet;'});
downloadFile(content);

Alternatively, you can extract the headers from your response, store the filename in a variable, and then provide that variable to the downloadFile() function.

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 files not being delivered by Express server

I have finished compiling my Angular front-end and placed it in the public folder of the Node.js back-end, which is now accessible from the browser: app.use(express.static('public')); I've also configured Express to serve the content: app ...

Searching through all values can be done by following these steps

Need help with implementing a search feature that can search all values in Angular2. Here's the current code snippet: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Is it feasible to utilize mat-selection-list with an object instead?

I've been exploring the mat-selection-list feature available in the material.angular.io documentation at material.angular.io/components/list/overview Instead of using a string array, I'm aiming to utilize an array of objects. The documentation c ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

Angular UI and Node backend causing CORS issues

Just diving into the world of node and could use a little assistance. Encountering this error message: Access to XMLHttpRequest at 'http://localhost:3000/api/auth/signin' from origin 'http://localhost:4200' has been blocked by CORS pol ...

When using Angular server-side pagination with ngrx and Express in Node.js, I often encounter discrepancies in the indexing across different stacks

After successfully implementing server-side pagination in Angular, I encountered an issue where the page was set to 1 initially, but the mat-paginator component started at index 2. Despite functioning correctly when changing pages, this discrepancy puzzled ...

What could be causing the error I encounter when attempting to send JSON in a GET request?

Currently, I am utilizing Angular 10 in my project. I am attempting to send an object in a GET request, so I decided to convert it to JSON: getData(dataPlan: Data): Observable<Response<InfoType[]>> { return this.client.get<Response< ...

The type is lacking the following properties in array.push

Encountering an issue with the register page in my IONIC app. Currently, I am utilizing a data.json file to store all user data, and I aim to create a new member with minimal information required (name, email, password) while leaving other fields empty fo ...

Arranging an array of objects based on a specific keyword and its corresponding value

I have an array of objects that looks like this: [ { "type": "Exam", "value": 27 }, { "type": "Lesson", "value": 17 }, { "type": "Lesson", &qu ...

How can I combine my two ngIf conditions into an ngIf else statement?

Having trouble incorporating an *ngIf else with two large <div> elements, as the content seems overwhelming to organize properly while following the documentation. Initially believed that using the same styling for two open text boxes, with one hidd ...

Issue: Unable to link with 'dataSource' as it is not a recognized feature of 'mat-tree'

Upon following the example provided at https://material.angular.io/components/tree/overview, I encountered an error when trying to implement it as described. The specific error message is: Can't bind to 'dataSource' since it isn't a kn ...

Combining numerous interfaces into a unified interface in Typescript

I'm struggling to comprehend interfaces in Typescript, as I am facing difficulty in getting them to function according to my requirements. interface RequestData { [key: string]: number | string | File; } function makeRequest(data: RequestData) { ...

Issue with refreshing causing Firebase Hosting (utilizing Angular 8 and Service Worker) to not update

I am the owner of quackr.io and I am encountering an issue where users are not seeing the updated version of my code. Quackr is a Progressive Web App (PWA) built with Angular SSR and Service worker, deployed on Firebase hosting. Every time I deploy a new ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Creating a customized Angular Material 2 component that utilizes the NG Value Accessor feature

Trying to create a custom component in Angular 4.4 + material beta12, but having trouble identifying the issue in my implementation. Here is the custom input I am attempting to achieve: https://i.sstatic.net/HCHLV.jpg Goal: Set a value to formControl ...

Error encountered when attempting to import Angular Version 9.1.4: TS2314 error code

I recently created a custom Angular library using version 9.0.7 of Angular. This library was successfully imported into applications running the same version without any issues. However, when attempting to import this library into an Angular app running ve ...

Utilizing generics with Swagger in NestJS

export class PaginatedResult<T> { @Expose() @ApiResponseProperty(type: T}) // It's unfortunate that this isn't working because it's a type but being used as a value @Transform(({ obj }) => obj.data.map((data) => new obj.cla ...