In my HTML document, there is a image
<img src="https://www.gravatar.com/avatar/1d9c87a4d5cbcae4c76e867cb6861fa0?s=48&d=identicon&r=PG&f=1"/>
When open this document in browser, E.g. Chrome, we can find the Content-Type
of this image is "image/png"
in Chrome Developer Tools -> Network tab according to the HTTP response headers.
How can I get the Content-Type
using JavaScript after the image loading.
More specifically, what I need is a function like below.
/**
* @param {HTMLImageElement} img
* @return {String} the content type, e.g. "image/png", "image/svg+xml"
*/
getImgContentType(img) {
// TODO
}
You will need to make HEAD request to fetch headers. Here is another simple version using fetch API could look like this:
getImgContentType (img) {
return fetch(img.src, { method: 'HEAD' })
.then(response => response.headers.get('Content-type'))
}
And usage would be:
obj.getImgContentType().then(type => {
console.log(type)
})
Also note, that getImgContentType
's interface needs to be asynchronous. It's convenient to return promise.
Using a XMLHttpRequest of type HEAD
(type HEAD
means that the request will only recieve the header data, the image won't be redownloaded):
getImgContentType(img) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", img.src, true);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
console.log(xhr.getResponseHeader("Content-Type")); // type
console.log(xhr.getResponseHeader("Content-Length")); // size
// ...
}
};
xhr.send();
}
Just note that not all servers implement HEAD
requests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With