Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows:

  {
  "format": // file extn ----only xls
  "docTitle": //file name
  "document" :// base 64 encoded data
  }

The attempt was made to handle the API on the frontend by decoding the 'document' key using the atob() function.

  downloadTemplate() {
  this.fetchData.fetchDownloadTemplate().subscribe(
  res => {
    let docString = atob(res.document);
    let format = res.format;
    let fileName = res.docTitle;

    let file = new Blob([docString], {type: "text/xls"});

    let url = URL.createObjectURL(file);
    let dwldLink = document.getElementById('template_link');
    dwldLink.setAttribute("href", url);
    dwldLink.setAttribute("download", fileName);
    document.body.appendChild(dwldLink);
    dwldLink.click();
  },
  err => {
    console.log(err.responseJSON.message);
  })
  }

However, there seems to be corruption in the data. After some investigation, it was discovered that atob() decodes using the ASCII charset, whereas the encoding was done using the UTF-8 charset.

If you have any suggestions for an alternative method to decode the data with UTF-8 charset in TypeScript, please share. The Angular (v4+) project I am currently working on throws an error when using JS validators.

Answer №1

During my quest to find a module that could handle Unicode to binary conversion, I stumbled upon

https://github.com/dankogai/js-base64#decode-vs-atob-and-encode-vs-btoa

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

The Base64.decode() functionality supports utob decryption.

This module is compatible with Angular (v4+) and also includes dependencies for Typescript (2).

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

Utilize JavaScript to establish an object with key and value pairings

Wanting to loop through and create an object that contains key => [value], if the key already exists, simply add the value. Here is what I have tried so far: let dataName = []; let obj = {}; checkboxes.forEach(checkbox => { if (checkbox.che ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

What could be causing Typescript Compile Errors to occur during runtime?

In the Visual Studio React + Redux template project, I have created a react component with the following "render()" method: public render() { return ( <React.Fragment> <h1>Welcome to the Adventure Company {th ...

Exploring how to iterate through an object to locate a specific value with TypeScript and React

I am looking to hide a button if there is at least one order with status 'ACCEPTED' or 'DONE' in any area or subareas. How can I achieve hiding the "Hide me" menu item when there is at least one area with orders having status 'ACCE ...

Error: The property 'rtl' is not defined and cannot be read

I'm currently in the process of developing a vuejs component library that utilizes vuetify 2.1.4 and attempting to import it into another application locally through npm link. However, I'm encountering numerous errors such as TypeError: Cannot ...

Problem with jQuery Window Resize Trigger Not Reactivating

I am facing a challenge in integrating a slider within multiple jquery tabs. As the slider requires specific width and height to display correctly, I have to trigger a window resize event when the tabs are switched. Surprisingly, the code I implemented onl ...

Matching the appropriate data type for interface attributes

In the process of developing a module (module1), I have defined the following interface type: interface ModuleOneInterface { keyOne: customInterface; keyTwo: customInterface; keyThree: customInterface; } Now, as I work on another module (modul ...

Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages. The homepage features a functional filter section that enables users to search for offers based on different ...

Angular 2 communication between parent and child components

I am having trouble incorporating an action button in the child_1 component, while the event handler is located in the sub child component, child_2. Here's a snippet of the code: app.component.html (Parent HTML) <div style="text-align:center"> ...

What is the best way to include the Mailchimp integration script in the `Head` of a Next.js project without causing any pre

Hello there Incorporating mailchimp integration into my nextjs site is proving to be a challenge. I've been attempting to add the following code snippet to next/Head within my custom _document <script id="mcjs">!function(c,h,i,m,p){m= ...

What is the best way to access an excel file using JavaScript and Protractor?

Is it possible to read an Excel file dynamically in JavaScript and iterate through cell values using row and column counts, without converting it into a JSON object? I have searched through several posts on Stack Overflow but have not found a solution yet. ...

Enhancing the NextPage Typescript Type: A Step-by-Step Guide

I'm working on a NextJS dashboard with role-based access control and I need to pass an auth object to each page from the default export. Here's an image showing an example of code for the Student Dashboard Home Page: Code Example of Student Dashb ...

Retrieving the `top` value using `$this.css("top") can either return an object or an element value

Something odd is happening with my HTML object: <div data-x="1" data-y="1" class="tile empty" style="top: 32px; left: 434px;"> <div class="inner">1:1</div> </div> When attempting to access its top property in jQuery using the ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

Define the interface for a GraphQL resolver argument in code-first implementation

This specific GraphQL schema example from the Constructing Types page showcases how to define the Query type. // Creating the Query type var queryType = new graphql.GraphQLObjectType({ name: 'Query', fields: { user: { type: userType ...

Incorporate Sendbird into Angular 6 for seamless communication integration

I recently started delving into the world of angular6 and nodejs. I am eager to integrate sendbird with Angular6, but I'm struggling to find a clear starting point. If anyone has successfully done this before, I would greatly appreciate some guidance ...

The loading of charts and animations is sluggish on mobile devices

My Chart.js chart starts with 0 values and updates upon clicking submit to load data from an external database. While this works efficiently on a computer browser, the load time is significantly longer when accessing the page on a mobile device. It takes a ...

What do you call the syntax %< ... >%?

Observed zoomInAnimation : true, zoomOutScale : false, templateLegend : "<ul class=\"<%=type.toLowerCase()%>-legend\"><% for (var j=0; j<sections.length; j++){%><li><span style=\"background-color:<%=section ...

Innovative application transforms rigid input with dynamic hyphens

I am currently working on an input field specifically designed for Social Security Numbers (SSNs). My aim is to have an input with pre-placed hyphens, allowing the user to simply enter their 9-digit SSN while the numbers automatically space themselves arou ...

Surprising Outcome when Dealing with Instance Type - Allowing extra properties that are not explicitly stated in the type

I've come across an issue with the InstanceType Utility Type. I am trying to create a function that takes a class constructor and an instance of that class. For instance: export type Class<T=any> = { new(...args: any[]): T; }; function acceptC ...