Encountering the issue of receiving type [object object] in file content rather than a blob when downloading a file with Angular 7

When using Angular 7, I encountered an issue while calling an API with the GET method and attempting to download a file using the 'saveAs' function from the fileSaver library.

After retrieving the filename from the response header, I found that I was unable to properly download the file. Instead, I received '[Object object]' in the file content. However, everything worked fine when using a dummy name.

This is my component file:

         fileName:string="";
         const MIME_TYPE ={
         XLSX:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
         TXT:'text/*',
         PDF:'application/pdf'
         }
         downloadFile(){
           this.DownloadService.downloadFile(
          (data: any) => {
           this.fileName=data.headers.get('fileName');
            const EXT = this.fileName.substr(this.fileName.lastIndexOf('.')+1);
            saveAs(new Blob([data],{type:MIME_TYPE[EXT]}),this.fileName);
          }
        );
    }

Here is the DownloadService file:

  public downloadFile(callback: (responseData: any) => void): void {
        this.apiService.downloadFile.subscribe((data: any) => {
          if (callback) {
            callback(data);
          }
        });
      }

And here is the apiService file:

  downloadFile(param: any): Observable<any> {
          return this.http.get(api/download, {responseType:'blob',observe: 'response' });
        }

The output in the file content is:

[Object object]

Answer №1

There are several important factors to take into account.

  1. In certain scenarios, it may be necessary to use JSON.Stringify() on the binary data before creating a new Blob if the blob type is HTML/TXT.

  2. If Base 64 encoding is being used, encoding should be done on the server and response parsing on the front end (see code snippet below).

export const base64ToArrayBuffer = (base64) => {
    const binaryString = window.atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    return bytes.map((byte, i) => binaryString.charCodeAt(i));
};

  1. It's also important to consider the Headers sent by the server returning the file. Some HTTP requests may not handle the response correctly due to incorrect Headers being sent. Packages like Axios rely on these headers for proper response parsing. To avoid any discrepancies, setting "responseType" to "blob" may be necessary.

This information may come in handy for any time travelers visiting from the future.

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 ng-repeat with toggle filter

Looking for a way to display data in an angular application using ng-repeat? Want to add and remove filters on the displayed data with a simple click? You're in luck. Implementing a toggle filter functionality is easier than you think. If you've ...

How to align elements both in the center and off-centered within a Bootstrap 4 container

Using Bootstrap 4, I have a container-fluid where I placed a logo in the center. <div class="container-fluid d-flex justify-content-center align-items-center"> <img src="logo.png"> <div> Now, I want to add an additional element acting ...

Translation of menu item label has not been executed

Here we have a component called SidebarMenuComponent that is not translating the labels of its menu items correctly. The goal is to get the labels translated, but the current implementation is failing. What is the correct approach to apply translation in t ...

Create a reusable React widget in a JavaScript file and integrate it into an ASP.NET MVC project

Is there a way to create a widget with the React library and compile it into a single JavaScript file for reuse in any non-React application (particularly in ASP .NET)? ...

The webpage keeps crashing after attempting to load an object multiple times using THREE.js

Within my app, there are several buttons that trigger the loading of a new object onto the scene when clicked. Below is the code snippet responsible for this functionality: character = new THREE.UCSCharacter(); var ucspath = "skinnedModel.json"; manager ...

Encountering an issue with Jest when using jest.spyOn() and mockReturnValueOnce causing an error

jest --passWithNoTests --silent --noStackTrace --runInBand --watch -c jest-unit-config.js Project repository An error occurred at jest.spyOn(bcrypt, 'hash').mockRejectedValue(new Error('Async error message')) Error TS2345: The argum ...

Getting rid of the final ng-form from validation within angularjs

Within my AngularJS application, I have implemented a master detail form for handling transactions. The form consists of standard master data fields such as Name and Type, along with a detailed section that allows users to add and delete multiple lines. Ea ...

When using express-jwt-blacklist, I encountered an issue where an error was thrown indicating "Error: JWT missing tokenId claimsub"

I am currently working on a MEAN stack application where I have implemented session authentication using express-jwt. Everything works fine with the express-jwt token, but I encountered an issue when trying to handle logouts by removing or blacklisting jw ...

Trouble with AdView: encountered ClassNotFoundException for org.json.JSONException

Despite not using JSON in my app, I am encountering a JSON error. Can someone please assist me with this issue? The app works fine when I remove com.google.ads.AdView, but then the ads stop working. I am running Android 4.2 and have added admob.jar to my l ...

Positioning of a paper-dialog in Polymer

I'm currently utilizing polymer's paper-dialog element in my application. While the dialog is always centered by default, I am looking to establish a minimum distance between the dialog and the right side of the window. This way, as the window re ...

Generating a dataframe with pandas using JSON data

I'm facing a challenge creating a table from nested JSON data. The JSON response obtained from the Coinmarketcap API request: data = {'status': {'timestamp': '2020-05-05T21:34:45.057Z', 'error_code': 0, 'e ...

Is there a way to display the console output on an Angular webpage?

I'm currently working on a Django project that utilizes Angular as its frontend. One of the features in my application is a button that triggers a scan of the database tables upon clicking. The results of this scan are printed continuously to the IDE ...

Permanently alter the background color of the DIV

Is there a way to permanently change the background color of a div tag after it has been clicked? I tried the code below: div { min-height: 50px; background-color: yellow; border-radius: 4px 4px 0 0; padding: 10px; display: flex; align-items: center ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

Tips for reducing unnecessary words in your writing style

Is there a way to simplify the handleSubmit function by creating a new interface and using eventDefault? How can I achieve that? import {Project} from "../ProjectsPage/Project"; interface FormTypeProps { onCancel: () => void; onSa ...

Utilize a random file import with the help of React JS, Babel, and ES6

Having trouble displaying a random image using webpack. I have a directory with various images, such as: 1.jpg, 1-cropped.jpg 2.jpg, 2-cropped.jpg I want to fetch a random image from this directory without manually adding a reference for each file. I&apo ...

Problem with Express Server related to MIME type ('text/html') is occuring

Recently, I started learning about Express server module in my school. To practice, I created a simple website but encountered an issue with the CSS file not being executed (checked using Chrome's terminal). Refused to apply style from 'http://l ...

Tips for finding a specific key-value pair within a JSON data structure

[ {"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"}, {"category":["34","37","47"],"type":"30 days","price":"200","ID":1}, {"category":["46"],"type":"40 days","price":"100","ID":2} ] To retrieve all categories that have the type: 30 day ...

Combine all Axios requests into a single reusable function

This question is regarding code refactoring and axios requests. I have noticed that in my code, there are multiple calls made to the same url with similar structures. To avoid repetition and improve efficiency, I am thinking of creating a helper function ...

Looking to create a full-width image slider for your webpage without using absolute positioning? Here's how!

Recently, I added a Slider to my website officesincambridge.co.uk. I decided to make the slider go the full width of the page by adjusting the div it was wrapped in: .custom-slider { position:absolute; //added left: 0; //added width: 100%;} This c ...