Search code examples
javascriptimagetokenonloadbearer-token

onload function with token bearer javascript


I have my function

function setImg(imgUrl){
    img.src = imgUrl
    img.onload = function () {
    ctx.canvas.width  = this.width;
    ctx.canvas.height = this.height;
    ctx.drawImage(img, 0,0);
    updateData(lastData)
  };

required to upload image size and put in a canvas. The bearer token is required to upload the image.

I already tried to to ad the beginnig of the function

img.src = imgUrl + '?access_token=xxxxxxxxxxxx';

But it didn't work. I have to do it with pure js, i saw all the others questions but none were helpful. Someone can help?


I tryed also to do inside setImg

    let tmp1;

var oReq = new XMLHttpRequest();
oReq.open("GET", imgUrl, true);
oReq.setRequestHeader("Authorization", "Bearer xxxxxx");
// use multiple setRequestHeader calls to set multiple values
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var u8 = new Uint8Array(arrayBuffer);
    var b64encoded = btoa(String.fromCharCode.apply(null, u8));
    var mimetype="image/png"; // or whatever your image mime type is
    // document.getElementById("yourimageidhere").src="data:"+mimetype+";base64,"+b64encoded;
    tmp1 = "data:"+mimetype+";base64,"+b64encoded;
  }
};
oReq.send(null);

img.src = tmp1;
img.onload = function () {
  ctx.canvas.width  = this.width;
  ctx.canvas.height = this.height;
  ctx.drawImage(img, 0,0);
  updateData(lastData)
};

but it didn't work.


Solution

  • const src = imgUrl;
    const options = {
      headers: {
        'Authorization': 'Bearer xxxxxxx'
      }
    };
    
    fetch(src, options)
    .then(res => res.blob())
    .then(blob => {
      // console.log("AAA", URL.createObjectURL(blob) );
      img.src = URL.createObjectURL(blob);
    });