How to get <img> content-type using javacript after loading
There is an image in my HTML document
<img src="https://www.gravatar.com/avatar/1d9c87a4d5cbcae4c76e867cb6861fa0?s=48&d=identicon&r=PG&f=1"/>
When opening this document in a browser eg. Chrome, we can find Content-Type
this image "image/png"
in Chrome Developer Tools -> Network under the HTTP response headers.
How can I get Content-Type
using JavaScript after the image is loaded.
Specifically, I need a function like below.
/**
* @param {HTMLImageElement} img
* @return {String} the content type, e.g. "image/png", "image/svg+xml"
*/
getImgContentType(img) {
// TODO
}
source to share
Using XMLHttpRequest type HEAD
(type HEAD
means the request will receive header data, the image will not be reloaded):
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();
}
Please note that not all servers implement requests HEAD
.
source to share
You will need to make a HEAD request to retrieve the headers. Here's another simple version using the fetch API that might look like this:
getImgContentType (img) {
return fetch(img.src, { method: 'HEAD' })
.then(response => response.headers.get('Content-type'))
}
And the usage would be:
obj.getImgContentType().then(type => {
console.log(type)
})
Also note that the interface getImgContentType
must be asynchronous. It is convenient to return a promise.
source to share