Angular 4 - convert base 64 to a downloadable file

佐手、 提交于 2019-12-11 18:07:58

问题


I have a Rest web service that returns a json object, one of the attributes contains a base 64 string which represents a simple file, this is an example of the JSON object :

{
  "id": 9,
  "name": "Step ",
  "orderOf": 0,
  "description": "desc",
  "script": null,
  "file1": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPGptZXRlclRlc3RQbGFuIHZlcnNpb249IjEuMiIgcHJvcGVydGllcz0iNC4wIiBqbWV0ZXI9IjQuMCByMTgyMzQxNCI+CiAgPGhhc2hUcmVlPgogICAgPFRlc3RQbGFuIGd1aWNsYXNzPSJUZXN0UGxhbkd1aSIgdGVzdGNsYXNzPSJUZXN0UGxhbiIgdGVzdG5hbWU9IlRlc3QgUGxhbiIgZW5hYmxlZD0idHJ1ZSI+CiAgICAgIDxzdHJpbmdQcm9wIG5hbWU9IlRlc3RQbGFuLmNvbW1lbnRzIj48L3N0cmluZ1Byb3A+CiAgICAgIDxib29sUHJvcCBuYW1lPSJUZX",
  "file2": "IyBTYW1wbGUgdXNlci5wcm9wZXJ0aWVzIGZpbGUNCiMNCiMjICAgTGljZW5zZWQgdG8gdGhlIEFwYWNoZSBTb2Z0d2FyZSBGb3VuZGF0aW9uIChBU0YpIHVuZGVyIG9uZSBvciBtb3JlDQojIyAgIGNvbnRyaWJ1dG9yIGxpY2Vuc2UgYWdyZWVtZW50cy4gIFNlZSB0aGUgTk9USUNFIGZpbGUgZGlzdHJpYnV0ZWQgd2l0aA0KIyMgICB0aGlzIHdvcmsgZm9y"
}

I want to have those both files as downloadable, which consists of converting the base 64 string to a Blob then calling FileSaver library to export them as files, but all I get is a file filled literrally with the base 64 string.

This is my try :

downloadFile(file: Blob) {
    if (file !== null && file !== undefined) {
      var blob = new Blob([file], {type: 'text/plain'});
      saveAs(blob, "test.properties");
    }
  }

How do I convert those attributes in order to download a file's real content.


回答1:


In your file1 and file2 attributes, you have b64 encoded string.

Here is a function to convert b64 to blob, try this :

public base64ToBlob(b64Data, contentType='', sliceSize=512) {
    b64Data = b64Data.replace(/\s/g, ''); //IE compatibility...
    let byteCharacters = atob(b64Data);
    let byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        let slice = byteCharacters.slice(offset, offset + sliceSize);

        let byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        let byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    return new Blob(byteArrays, {type: contentType});
}

So you can use your function like this

downloadFile(b64encodedString: string) {
    if (b64encodedString) {
      var blob = base64ToBlob(b64encodedString, 'text/plain');
      saveAs(blob, "test.properties");
    }
}


来源:https://stackoverflow.com/questions/49774559/angular-4-convert-base-64-to-a-downloadable-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!