Javascript Blob anchortag download produces corrupted file

the following code downloads a file that can't be opened(corrupt) and I have absolutely no idea why. I've tried this in so many ways but it never works, it always produces a corrupt file. The original file isn't the problem because it opens fine. I'm trying to open mp4, mp3, and image files.

//$scope.fileContents is a string

$scope.fileContents = $scope.fileContents.join(",");
        var blob = new Blob([$scope.fileContents], {type: $scope.file.fileDetails.type});
        var dlURL = window.URL.createObjectURL(blob);
        document.getElementById("downloadFile").href = dlURL;
        document.getElementById("downloadFile").download = $scope.file.fileDetails.name;
        document.getElementById("downloadFile").click();
        window.URL.revokeObjectURL(dlURL);

Answers


You need to download the file contents as binary using an ArrayBuffer e.g.

$http.get(yourFileUrl, { responseType: 'arraybuffer' })
    .then(function (response) {
        var blob = new Blob([response.data], {type: $scope.file.fileDetails.type});
        // etc...
    });

Sources:


Need Your Help

Gulp Sass logError and gulp-notify at same time?

javascript node.js sass gulp gulp-sass

I have my gulp sass task setup so it doesn't crash my gulp watch: