angular-file-saver download base64 file using FileSaver

20,684

I ended up digging into BLOB and came across this stackoverflow to get it working. Creating a Blob from a base64 string in JavaScript

Share:
20,684
Harbinger
Author by

Harbinger

I'm a software engineer with about a years worth of experience. My first 6 months I spent building an ASP.NET MVC web application from scratch. This last 6 months I've been building Angular directives to distribute to other angular applications. Directives I've built encapsulate Security and the necessary API calls to make it very basic for other application teams to implement an element level directive. I learn new technologies through books, conferences, and pluralsight.

Updated on July 07, 2022

Comments

  • Harbinger
    Harbinger almost 2 years

    I'm trying to download a file that is base64 using angular-file-saver.

    I can do this without angular-file-saver with just this html mark-up:

    <a ng-href="data:{{document.mimeType}};base64,{{document.base64Code}}" target="_blank" download>Download Single Document</a>
    

    I have other needs now that are fulfilled with angular-file-saver that are causing me transition to doing this with FileSaver. Now I want to implement the same download using file saver. My html mark-up is:

    <a ng-href="#" ng-click="downloadFile()">Download with File Saver</a>
    

    Then I build up my downloadFile function like this:

    function downloadFile () {
            var data = new blob([$scope.document.base64Code], {type: $scope.document.mimeType+';base64'});
            var config = {
                data: data,
                filename: $scope.documentSaveAs ? $scope.documentSaveAs : $scope.document.FileName
            }
            fileSaver.saveAs(config);
        }
    

    My issue is that after the file downloads when I attempt to open it the file is corrupt.

    I'm assuming that I'm doing something wrong with the type object by concatenating ";base64". I've started digging into angular-file-saver.bundle.js but any help is greatly appreciated. What am I doing wrong?

  • Harbinger
    Harbinger over 8 years
    Just to add to the answer I would recommend adding npm validator to your solution. You can verify your sting is base64 before trying to download or convert to blob.