【问题标题】:File created with blob does not support NON-ASCII characters使用 blob 创建的文件不支持非 ASCII 字符
【发布时间】:2018-01-12 02:34:45
【问题描述】:

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

这是代码。

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 页面的 head 部分使用了 <meta charset="utf-8">

【问题讨论】:

  • 将文本编码设置为 UTF8 或任何输入编码格式。
  • 这不是这样吗? {type: response.headers['content-type'] + ";text/csv;charset=utf-8"}
  • 尝试将字符集更改为 ISO-8859-1ISO/IEC 8859-15
  • 问题是,文本以包含文档的编码显示。因此,请确保您的原始 html 文档带有 UTF-8 标头和元标记,以便浏览器使用 UTF-8。
  • @Tschallacka 字符编码为utf-8

标签: javascript angularjs blob single-page-application


【解决方案1】:

没有必要使用整个ctrl.downloadFile()。相反,我使用了一个函数来制作下载链接,然后在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>

如果不需要动态制作下载链接,直接使用ng-href中的链接即可。

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

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 2013-03-10
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多