1

Currently using

https://github.com/stranger82/angular-utf8-base64

and

https://github.com/eligrey/FileSaver.js/

to decode a base64 encoded PDF file which I am fetching from a rest API.

It decodes and downloads just fine, however when I try view it, it's blank.

I have looked at

AngularJS: Display blob (.pdf) in an angular app

and tried adding

responseType: 'arraybuffer'

to my get request however, this causes the response to be null with no data being returned from the get request.

Other files seem to download and render just fine.

Any help would be much appreciated as always!

Code:

          function save() {
            var fileContent = base64.decode(response.File.fileContent);
            var file = new Blob([fileContent], {type: response.File.contentType});
            saveAs(file, response.File.name);
          }

        $http.get(url.join('')).success(function(response) {
            save(response);
        }).error(function(error) {
            console.log('The following error has occured' + error);
        });
Community
  • 1
  • 1
user2085143
  • 4,162
  • 7
  • 39
  • 68

1 Answers1

0

In case the API Rest retrieves an array of bytes you can simply use this js function

OBS: data.payload must be an array of bytes Calling the function : DownloadService.download(data.payload, 'downloadExcel', 'xls'); DownloadService.download(data.payload, 'downloadPDF', 'pdf');

(function() {
    'use strict';

    angular
        .module('fileUtils')
        .service('DownloadService', DownloadService);

    DownloadService.$inject = ['$window'];

    function DownloadService($window) { // jshint ignore:line

        this.download = function (fileBytes, name, type) {
            var fileName = '';
            if (name) {
                 fileName = name + '.' + type;
            } else {
                 fileName = 'download.' + type;
            }

            var byteCharacters = atob(fileBytes);
            var byteNumbers = new Array(byteCharacters.length);
            for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);

            var file = new Blob([byteArray], { type: 'application/' + type });

            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(file, fileName);
            } else {
                //trick to download store a file having its URL
                var fileURL = URL.createObjectURL(file);
                var a = document.createElement('a');
                a.href = fileURL;
                a.target = '_blank';
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
            }
        };
    }
})();
Tiago Medici
  • 1,944
  • 22
  • 22