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

What are some ways to enhance the design of Material Input Text boxes and make them more compact?

I have been developing an Angular application using Material UI v7, but I am finding that the input controls are not as compact as I would like them to be. I have attempted to customize them without success. Can someone provide guidance on how to achieve m ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

How can I ensure that each callback is passed a distinct UUID?

I am utilizing a package called multer-s3-transform to modify the incoming image before uploading it to my bucket. Below is the code snippet of how I am implementing this: const singleImageUploadJpg = multer({ storage: multerS3({ s3: s3, bucket: ...

Retrieve data from Last.fm API by utilizing both Node.js and Angular framework

I am currently working on implementing the node-lastfmapi track.search method into my project. I have successfully retrieved the results, but I am facing challenges in integrating them into the front end using Angular. My backend is powered by mongoDB and ...

Preserving state during navigation and router refresh in Next.js version 13

In the component below, we have a Server Component that fetches and renders data. When router.refresh() is called on click, it reruns the page and refetches the data. However, there is an issue with Nextjs preserving the state. Even though the server compo ...

The swipe motion will be executed two times

By pressing the Circle button, the Box will shift to the right and vanish from view. Further details (FW/tool version, etc.) react scss Typescript framer-motion import "./style.scss"; import React, { FunctionComponent, useState } from &q ...

Can you explain the distinction between compiled and interpreted programming languages?

Despite my efforts to research the topic, I am still confused about the distinction between a compiled language and an interpreted language. It has been mentioned that this is one of the distinguishing factors between Java and JavaScript. Can someone ple ...

Launching npm start does not automatically open a browser tab

I'm currently learning angularjs 2 and I'm eager to create my first application using the framework. Following the guidelines on their official website, I proceeded with all the steps outlined in this link. In step 6, I am required to run the com ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

I must pause for a specified period before initializing the subsequent component in React Native

Due to restrictions on my API key, I can only make one request every 5 seconds. Therefore, I need to wait for 5 seconds before making another request for NearbyJobs (with the first request being made for PopularJobs). <ScrollView showsVerticalScrollIndi ...

What causes the discrepancy between the values returned by the jQuery getter css() method and JavaScript when accessing the style variable

After recently beginning to use jquery, I decided to switch due to initialization issues when loading external styles with javascript. Here is a rule defined in an external style sheet: #siteLogoDiv { position:absolute; left:0px; top:0px; width:100%; heig ...

MongoDB Node.js throws a RangeError when trying to push a message that exceeds the maximum call stack size

I'm currently delving into the world of building a MEAN app and encountering an issue when attempting to append a message to a messages array within my User Model. While I can successfully create a new message and pass the user object, I face an error ...

Create an interactive visualization using d3.js

Currently, I am on the hunt for a technology that can help me render a tree structure based on Json data. After researching options like graphViz and d3, it seems like d3 is more optimized for modern browsers. With the extracted Json data, my goal is to c ...

Understanding the implementation of setters in JavaScript: How are they utilized in Angular controllers?

After learning about getters and setters, I came across an example that clarified things for me: var person = { firstName: 'Jimmy', lastName: 'Smith' }; Object.defineProperty(person, 'fullName', { get: function() ...

Creating an entity using various asynchronous sources in node.js/express.js

Struggling to find a solution to my problem online and hoping someone here can help. My express route is making multiple API requests for different JSON objects, but I'm having trouble building a single JSON response for the client side view. All my a ...

Automatically arrange TypeScript import statements in alphabetical order in WebStorm / PhpStorm

I am using tslint with the default config tslint:recommended and I am looking to minimize the number of rules I need to customize. Some rules require that imports be alphabetized: src/core/task/TaskMockDecorator.ts[2, 1]: Imports within a group must be a ...

Is there a way to determine the most recent Typescript target compatibility for every Node version?

When using any version of Node, how can I identify the appropriate Typescript Compiler Option for target that offers the most functionality? I want to eliminate any guesswork. Specify the ECMAScript target version as: "ES3" (default), "ES5", "ES6"/"ES20 ...

Steps for running the function saved in variable `x`, with the value `function(){alert('a')}` assigned to it

How can I achieve this using javascript? var x = 'function(){ ... }' x = x.toFunction(); x(); Previously, I used var x = '...'; eval(x), but I have learned that this method is inefficient and slow. To provide some context, my goal is ...