Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
GlinesMome Avatar asked Jun 10 '13 05:06

GlinesMome


3 Answers

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
  })
like image 161
Aleksander Blomskøld Avatar answered Nov 15 '22 03:11

Aleksander Blomskøld


You can do this with jQuery:

$.ajax({
    url:'/someUrl',
    type: 'GET',
    success:function(res, status, xhr){
        var contentType = xhr.getResponseHeader('Content-Type');
    }
});
like image 20
karaxuna Avatar answered Nov 15 '22 05:11

karaxuna


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)

like image 35
Ebrahim Avatar answered Nov 15 '22 04:11

Ebrahim