带有令牌承载的 onload 函数 javascript

onload function with token bearer javascript

我有我的功能

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)
  };

要求上传图片大小,并输入canvas。上传图片需要不记名令牌。

我已经尝试在函数的开头添加广告

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

但是没有用。我必须用纯 js 来做,我看到了所有其他问题,但 none 很有帮助。有人可以帮忙吗?


我也试过在 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)
};

但是没用。

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);
});