从离子2中的XHR请求获取BLOB数据

时间:2018-08-23 06:26:43

标签: ionic-framework ionic2 xmlhttprequest blob

任何一个电话如何在ionic 2中获取Blob XHR请求和XMLHttpRequest,我都必须从api获取图像URL。

这是我的Ajax代码,我想要使用ionic 2

xhr.open('GET', "https://getbytitle('LE_COE_Mapping')/items(2)/AttachmentFiles('3.jpg')/$value");
    xhr.responseType = 'blob';
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   // xhr.setRequestHeader('Authorization', 'Token token="' + token + '"');
    xhr.setRequestHeader('Authorization', token); 
xhr.onload = function (e) {

        var img = new Image();
        var url = window.URL || window.webkitURL;
        img.src = url.createObjectURL(this.response);
        document.getElementById('Doctitle').appendChild(img);
       // alert(url.createObjectURL(this.response));
    };

    xhr.send(); 

请问最近两天我一直被困在里面。

请帮助我。 谢谢

2 个答案:

答案 0 :(得分:1)

我一次也遇到了同样的问题:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState == 4 && this.status == 200){
        //this.response is your final response
        console.log(this.response, typeof this.response);
        var img =  // your img syntax
        //your any custom code goes here
    }else{
  //show error message if you want to show
}
}
xhr.open('GET', 'http://Your image url');// image url be like http://ab.cd/img.png
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   //send authorisation if you sending token 
xhr.send(); 

希望这会对您有所帮助。

答案 1 :(得分:0)

我在下面解决了什么: this.array:这是我们传递的网址,用于获取特定网址的Blob网址:

const headers1 = new HttpHeaders({
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': "Bearer " + this.accessToken,
                'X-Requested-With': 'XMLHttpRequest'
              })
               const response = await this.http.get(this.array + "/$value", { headers: headers1, responseType: 'blob' }).toPromise();

              let b: any = new Blob([response], { type: 'application/octet-stream' });
              var url = window.URL.createObjectURL(b);
              console.log("this is url BLOB   " + url);