Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

javascript - Image request with different headers

I have an Img field on the page that is loaded from an external source:

<img src="wwww.external-source.com"/>

The image will be loadded is according to the user-agent. Is there a way to hook the request while loading the image so that the headers can be changed? If this is not possible, is it possible to cancel the loading process,and send another request instead?

Thanks

question from:https://stackoverflow.com/questions/65899259/image-request-with-different-headers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to use different headers for image, I would suggest you to use fetch api to download the image with customer headers like:

fetch("https://i.picsum.photos/id/525/200/300.jpg?hmac=Dhg6JV7Cl1oDtYMG0pq3hVUbGQjEpOX41178aR7_eh8", {
  headers: {
    "Some": "header",
  }
})
  .then(resp => resp.blob())
  .then(blobData => {
    console.log(blobData)
    const reader = new FileReader();
    reader.readAsDataURL(data);
    reader.onloadend = function () {
      const base64data = reader.result;
      // this is the data you can use in src attribute of img
      console.log(base64data);
    }
  });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...