GlinesMome
GlinesMome

Reputation: 1629

Getting the Content-Type with AngularJS or jQuery

I want to make a directive with AngularJS which displays a media (an image or a video).

To achieve this goal I have to determine the kind of media, in order to do that I wanted to make an AJAX reqest to the url and get the Content-Type header, but I have not find something like that in the documentation.

Have you some hints to do that?

Upvotes: 5

Views: 3381

Answers (3)

Ebrahim
Ebrahim

Reputation: 1818

After more than two hours of searching, this is the best answer I found for angularJS 1.x:

$http({
    method: method,
    url: url,
    data: data,
    header: {'Content-Type': 'application/x-www-form-urlencoded'},
    timeout: 30000
})
    .then(
        //success function
        function(response){
            console.log(response.headers('content-type'));
        },
        //error function
        function(response){
        }
    );

The main part is response.headers('content-type')

Note 1: This solution is applied to angular 1.x.

Note 2: This method is using then(success function,error function), which is much more better and reliable than the elder method (separate success and error)

Upvotes: 1

karaxuna
karaxuna

Reputation: 26940

You can do this with jQuery:

$.ajax({
    url:'/someUrl',
    type: 'GET',
    success:function(res, status, xhr){
        var contentType = xhr.getResponseHeader('Content-Type');
    }
});

Upvotes: 2

Aleksander Blomskøld
Aleksander Blomskøld

Reputation: 18552

You can get all the headers with $http:

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
      var contentType = headers('Content-Type');
      // use the content-type here
  })

Upvotes: 7

Related Questions