使用 blob 创建的文件不支持非 ASCII 字符

File created with blob does not support NON-ASCII characters

首先我要说类似的问题以前有人问过,但答案没有帮助。

这是代码。

ctrl.downloadFile = function (file) {
  var filename = file.filename.split("/"),
  name = (filename[filename.length - 1]);
  $http({method: 'GET', url: '/download/' + name}, {responseType: "blob"}).then(
    function success(response) {
      var blob = new Blob([response.data], {type: response.headers['content-type'] + ";text/csv;charset=utf-8,%EF%BB%BF"}),
        url = $window.URL || $window.webkitURL,
        fileUrl = url.createObjectURL(blob);
      var anchor = document.createElement('a');

      anchor.href = fileUrl;
      anchor.target = '_blank';
      anchor.download = name;
      anchor.style = "display: none";

      document.body.appendChild(anchor);
      anchor.click();

      setTimeout(function () {
        document.body.removeChild(anchor);
      }, 100);
    }
  )
};

这是调用 downloadFile() 函数的 html 代码。

<a  ng-click="$ctrl.downLoadFile(file)"  target='_blank'>{{file.filename}}</a>

下载的文件不支持德语特殊字符(ÅØÜ)。如何使文件支持这些字符?

更新1:我也这样做了。但是也没用。

var blob = new Blob(["\ufeff", response.data], 
                     {type: response.headers['content-type'] +
                      ";text/csv;charset=utf-8"})

更新 2:如果我使用这些字符(ÅØÜ)而不是 response.data.

   var blob = new Blob(["\ufeff", "Å Ø Ü" ], 
                         {type: response.headers['content-type'] +
                          ";text/csv;charset=utf-8"})

更新 3:这是一个单页应用程序。是的,我在 html 页面的头部部分使用了 <meta charset="utf-8">

使用整个 ctrl.downloadFile() 是不必要的。相反,我使用了一个函数来进行下载 link,然后在 ng-href 中调用它。

ctrl.urlForFile = function(file) {
  var split = file.filename.split("/");
  return '/download/' + file['xyz'] + "/" + split[split.length - 1];
};

<a ng-href="{{$ctrl.urlForFile(file)}}" target='_blank'>{{file.filename}}</a>

如果不需要动态下载link,直接在ng-href中使用link。

<a ng-href="/download/xyz/dfdsf23423423" target='_blank'>{{file.filename}}</a>