且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS保存从Web API 2发送的图像文件

更新时间:2023-02-15 11:42:02


提供的值'arrayBuffer'不是XMLHttpRequestResponseType类型的有效枚举值。

The provided value 'arrayBuffer' is not a valid enum value of type XMLHttpRequestResponseType.

使用 arraybuffer 全部小写:

    $http({
        url: State.Endpoint + "/api/account/picture",
        method: "GET",
        //responseType: 'arrayBuffer'
        //USE arraybuffer lowercase
        responseType: 'arraybuffer'
        //OR
        //responseType: 'blob'
    })

当responseType无效时,XHR API默认将响应解码为UTF-8。这会破坏二进制文件,如JPEG图像。

When the responseType is not valid, the XHR API defaults to decoding the response as UTF-8. This corrupts binary files such as JPEG images.

有关更多信息,请参阅 MDN XHR Web API - responseType

For more information, see MDN XHR Web API - responseType.

而不是创建一个< a download>< / a> code>元素与JavaScript DOM操作,考虑使用AngularJS框架。

Instead of creating a <a download></a> element with JavaScript DOM manipulation, consider using the AngularJS framework.

这是一个变得活跃的下载按钮的示例之后从服务器加载数据:

This is an example of a Download button that becomes active after the data is loaded from the server:

<a download="data_{{files[0].name}}" xd-href="data">
  <button ng-disabled="!data">Download</button>
</a>

xdHref 指令

The xdHref Directive

app.module("myApp").directive("xdHref", function() {
  return function linkFn (scope, elem, attrs) {
     scope.$watch(attrs.xdHref, function(newVal) {
       if (newVal) {
         elem.attr("href", newVal);
       }
     });
  };
});

PLNKR上的演示