atswann atswann - 1 year ago 69
HTTP Question

setting Content-Type: in angular js post request

<input type="file" ng-model="articleimg" placeholder="upload related img">

{params {view:'view',articleimg:$scope.articleimg}})

I would like to know how and where to specify
the content-type: multipart/form-data in this angularjs post request?

Please assist.
the default seems to be "application/json, text/plain,"
which does not work with the image/file uploads.

if(isset($_FILES['articleimg'])===true ){
echo "sucessfull";
}else echo "unsuccessfull";

the code above alway echos unsuccessfull.

Answer Source

$ shortcut method in angular takes three parameters, url, request data and a config object in which you can set headers like below :

$'/someUrl', data, {headers:{'Content-Type': 'multipart/form-data'}}).then(successCallback, errorCallback);

In your case it will be :

        {params {view:'view',articleimg:$scope.articleimg}}, {headers:{'Content-Type': 'multipart/form-data'})

You can also construct the request object like below :

 method: 'POST',
 url: $scope.base_url+'create.php',
 headers: {
   'Content-Type': 'multipart/form-data'
 data: {params {view:'view',articleimg:$scope.articleimg}}

and then make the request like this :

$http(req).then(function(){...}, function(){...});

If you want to set common application wide headers , you can use default headers which will be added to all the requests by default like below :

$httpProvider.defaults.headers.common['Content-Type'] = 'multipart/form-data';

This will add the above mentioned content type for all the requests.

More information in the documentation here