简体   繁体   English

设置Content-Type:在angular js发布请求中

[英]setting Content-Type: in angular js post request

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

$http.post($scope.base_url+'create.php', 
            {params {view:'view',articleimg:$scope.articleimg}})
            .then(function(response){
                    console.log(response);
    });

I would like to know how and where to specify the content-type: multipart/form-data in this angularjs post request? 我想知道在angularjs发布请求中如何以及在哪里指定内容类型:multipart / form-data?

Please assist. 请协助。 the default seems to be "application/json, text/plain," which does not work with the image/file uploads. 默认值似乎是“ application / json,text / plain”,不适用于图像/文件上传。

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

the code above alway echos unsuccessfull. 上面的代码总是回显不成功。

$http.post shortcut method in angular takes three parameters, url, request data and a config object in which you can set headers like below : angular中的$ http.post快捷方式方法包含三个参数:URL,请求数据和一个配置对象,您可以在其中设置标题,如下所示:

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

In your case it will be : 您的情况将是:

$http.post($scope.base_url+'create.php', 
        {params {view:'view',articleimg:$scope.articleimg}}, {headers:{'Content-Type': 'multipart/form-data'})
        .then(function(response){
                console.log(response);
});

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 文档中的更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM