角度设置图像加载时的标题

时间:2017-03-24 10:02:16

标签: angularjs authentication imagesource request-headers

我必须在每个请求的HTTP标头中设置一个特殊值,以对服务器进行身份验证。

我有以下代码:

<img ng-if="content.image" src="{{img(content.image)}}">

var app = angular.module('myApp', []);
app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common['Authorization'] = 'myKey';
}])
app.controller('customersCtrl', function($scope, $http) {
    $http.get("http://localhost:8080/myPath") .then(function(response) {
        $scope.content = response.data;
    });

对于JSON请求一切正常,但我与图像一起拍摄。 你有什么提示吗?

1 个答案:

答案 0 :(得分:1)

我用

解决了这个问题
    // Image returned should be an ArrayBuffer.
var xhr = new XMLHttpRequest();

    //set Authorization Header
    xhr.setRequestHeader("Authorization", 'myKey');
xhr.open( "GET", "https://placekitten.com/500/200", true );

// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";

xhr.onload = function( e ) {
    // Obtain a blob: URL for the image data.
    var arrayBufferView = new Uint8Array( this.response );
    var blob = new Blob( [ arrayBufferView ], { type: "image/jpeg" } );
    var urlCreator = window.URL || window.webkitURL;
    var imageUrl = urlCreator.createObjectURL( blob );
    var img = document.querySelector( "#photo" );
    img.src = imageUrl;
};

xhr.send();