1

I have linked a JSON response on user's request to fetch an excel document, the response is in the manner

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

I tried to handle the API on Frontend by decoding the document key using 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);
  })
  }

But the data gets corrupted, On doing some research I got to know that atob() decodes using ASCII charset, while I have done the encoding using charset UTF-8.

Can you suggest any alternative method for decoding the data with UTF-8 charset in typescript, as the angular(v4+) project I am working throws error on using JS validators.

Ronit Oommen
  • 3,040
  • 4
  • 17
  • 25
  • There is one library for angular js, not sure if it works for angular 2. https://github.com/stranger82/angular-utf8-base64 – TruckDriver Oct 31 '17 at 08:48

1 Answers1

0

While searching for a suitable module which would support Unicode to binary conversion, I came across

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() support utob decrpyption.

The module supports angular(v4+), and also add dependencies for Typescript(2)

Community
  • 1
  • 1
Ronit Oommen
  • 3,040
  • 4
  • 17
  • 25