Downloaded document getting corrupted using Blob method in angularJS

后端 未结 1 1211
清歌不尽
清歌不尽 2020-12-19 21:25

Downloading a file used to work fine in my application until I upgraded Angular to the latest. Even now, the file is getting downloaded, but the issue is that it is getting

相关标签:
1条回答
  • 2020-12-19 21:45

    it looks like the code at https://hastebin.com/yivaterozi.js was updated from using deprecated $http.success() method to current $http.then(). Promise' success callback function (within then method) receives only one object argument: https://docs.angularjs.org/api/ng/service/$http. Deprecated 'success' method got more arguments (data, status, headers) and data already contained raw data. When using then(), data is located under data property of response, so try to change your $http call to:

    $http({
      method: 'GET',
      cache: false,
      url: fileurl,
      responseType:'arraybuffer',
      headers: {
        'Authorization': "Bearer " + $rootScope.userInfo.access_token,
        'Access-Control-Allow-Origin': '*'
      }
    }).then(function (data) {
      var octetStreamMime = 'application/octet-stream';
      var success = false;
    
      // Get the headers
      var headers = data.headers();
        ...
        ...
    

    please note that headers are fetched correct here from the data object and not from the third argument (just add var, since we removed empty arguments). Now in each place that you use data, change it to data.data, like:

    // Try using msSaveBlob if supported 
    var blob = new Blob([data.data], { type: contentType });
    

    or just change argument data to response and add var data = response.data; anf modify headers getter to headers = response.headers();:

    $http({
      method: 'GET',
      cache: false,
      url: fileurl,
      responseType:'arraybuffer',
      headers: {
        'Authorization': "Bearer " + $rootScope.userInfo.access_token,
        'Access-Control-Allow-Origin': '*'
      }
    }).then(function (response) {
      var octetStreamMime = 'application/octet-stream';
      var success = false;
    
      // Get data
      var data = response.data;
    
      // Get the headers
      var headers = response.headers();
        ...
        ...
    
    0 讨论(0)
提交回复
热议问题