alexchenco alexchenco - 2 months ago 9
Javascript Question

How to read the image type from an URL?

I encountered something very strange:

enter image description here

As you see the second last picture has jpg format but it's being displayed as

png
type. (This is the Network panel in Chrome.)

How can I get this
png
file type with JavaScript? (How can I get it's MIME type)?

Answer

You check the content-type response header. The appropriate value is listed in the Chrome network debugger. Alternatively, you can look it up on one of the many lists on the internet.

Assuming you are using jQuery

$.ajax({
  url: "[image url]",
  success: function(response, status, xhr){ 
    var contentType = xhr.getResponseHeader("content-type") || "";
    if (contentType === "image/jpeg") {
      // do something with jpg
    }
    if (contentType === "image/png") {
      // do something with png
    } 
  }
});

If you are using plain javascript use XMLHttpRequest.getResponseHeader() in stead.