Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...