通过Ajax成功访问Authenticated Image

时间:2017-07-10 12:02:48

标签: javascript jquery ajax

我有这个方法,我必须登录到“存储应用程序”并在html img中显示img但不知道如何解析第二个成功函数。

PD :我检查了控制台日志是否达到了这种成功方法。

setTimeout(function() {
  $.ajax({
    contentType: 'application/json',
    data: JSON.stringify({
      "username": "username",
      "password": "password"
    }),
    dataType: "json",
    processData: false,
    type: 'POST',
    url: pathStorage + "/api/login",
    async: false,

    complete: function(data) {
      var response = $.parseJSON(data.responseText);

      $.ajax({
        type: 'GET',
        url: pathStorage + "/web-app/files/" + id + "_imagen.jpg",
        headers: {
          "Authorization": response.token_type + " " + response.access_token
        },
        success: function(data) {

          //this dont works
          $('#idImg').prop('src', 'data:image/jpg;base64,' + data)
        }

      })
    }

  })
}, 1000)

1 个答案:

答案 0 :(得分:0)

感谢@Musa的回复,我设法设置了img,但必须导入fileapi.js 我在这里留下我的实际代码

setTimeout(function () {
  $.ajax({
     contentType: 'application/json',
     data: JSON.stringify({
       "username": "user",
       "password": "password"
       }),
     dataType: "json",
     processData: false,
     type: 'POST',
     url: sessionRutaStorage + "/api/login",
     async: false,

     complete: function (data) {
        var response = $.parseJSON(data.responseText);

        var xhr = new XMLHttpRequest()
        xhr.open('GET', storagePath + "/web-app/files/" + id + "_imagen.jpg", true);
        xhr.setRequestHeader("Authorization", response.token_type + " " + response.access_token )
        xhr.onreadystatechange = function() {
            if (this.readyState == 4 &&this.status == 200) {

               var img=document.getElementById('imgInfo');
               var url = window.URL || window.webkitURL;
               img.src = url.createObjectURL(this.response);
               img.setAttribute("src",url.createObjectURL(this.response))
                }
          };

         xhr.responseType = 'blob';
         xhr.send();

  }

 })
}, 1000)