2

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)?

alexchenco
  • 53,565
  • 76
  • 241
  • 413

2 Answers2

2

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.

Paul-Jan
  • 16,746
  • 1
  • 63
  • 95
0

Send a HEAD request and look at the content type.

var url = '/url/to/your/file.jpg',
    xhttp = new XMLHttpRequest();

xhttp.open('HEAD', url);
xhttp.onreadystatechange = function () {
    if (this.readyState == this.DONE) {
        console.log(this.getResponseHeader('Content-Type'));
    }
};
xhttp.send();
Andrey Shipilov
  • 1,986
  • 12
  • 14