简体   繁体   中英

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, Eg 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
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM