Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get <img> content-type using javascript after loading

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
}
like image 346
GentleMint Avatar asked Mar 09 '23 08:03

GentleMint


2 Answers

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.

like image 150
dfsq Avatar answered Apr 01 '23 00:04

dfsq


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.

like image 34
ibrahim mahrir Avatar answered Apr 01 '23 02:04

ibrahim mahrir