How to get correct URL in HTTP header?

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 https://jsfiddle.net/r2jf74dm/ 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!

  • Answer:

    jQuery will already convert the response based on the content type (check this http://github.com/jquery/jquery/blob/1.4.3/src/ajax.js#L662 for details) if you dont specify a type on the http://api.jquery.com/jQuery.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: https://github.com/markserbol/urlive

Mattpx at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.