angular-file-saver download base64 file using File

2019-06-10 23:02发布

问题:

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?

回答1:

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