Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 513
yoprogrammer Avatar asked Mar 15 '16 00:03

yoprogrammer


1 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:

  • angular solution
  • plain javascript solution
like image 124
Boris Joffe Avatar answered Oct 18 '22 08:10

Boris Joffe