简体   繁体   中英

How to get HTTP header (Content-Type) from URL with Javascript

Good afternoon! Here is what I am trying to achieve.

I have an input which allow the user to enter an URL (mostly for images) but it can also be a different type of file. I am searching for a way to verify that the url exists and also get the mime type.

Here is a jsfiddle of my javascript tests.

I found a way to do it using a PHP and AJAX with a function like that:

PHP:

function get_url_content_type( $url ) {

    $header = get_headers( $url, 1 );

    if ( isset( $header['Content-Type'] ) ) {

        return $header['Content-Type'];
    }
}

I am not sure that is the right way to do it, does anyone have better ideas?

Many thanks!

jQuery will already convert the response based on the content type (check this url for details) if you dont specify a type on the $.ajax() call.

So all you can do is check the type of the generated response, to deduce the Content-Type that was sent:

$.get("myPage.html", { }, function(data) {
  if(typeof(data) === "string") {
    //html
  } else {
    //JSON
  }
});

In this case, it doesn't work because google explicitly disables Cross-Origin Request on its hosted images. If you run your tests with Firebug enabled, you will get the message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/images/srpr/logo11w.png . This can be fixed by moving the resource to the same domain or enabling CORS.

However, enabling CORS will need some work at server side that I don't think google is willing to do.

EDIT:

If you want to generate a client-side preview of some files, try using something like:

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