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
358 views
in Technique[技术] by (71.8m points)

javascript - Set custom header for the request made from <img/> tag

Let's say I have a code like this:

<img src='images/whatever.jpj' width='' height=''/>

How to configure custom headers for this request?

Will appreciate any help.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I'm late here, but you can do this with XMLHttpRequest and a blob.

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; //so you can access the response like a normal URL
xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
        var img = document.createElement('img');
        img.src = URL.createObjectURL(xhr.response); //create <img> with src set to the blob
        document.body.appendChild(img);
    }
};
xhr.open('GET', 'http://images.example.com/my_secure_image.png', true);
xhr.setRequestHeader('SecretPassword', 'password123');
xhr.send();

If you want, you could check to make sure the blob's MIME type is an image.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...