【问题标题】:setting Content-Type: in angular js post request设置 Content-Type:在 Angular js 发布请求中
【发布时间】:2017-03-29 16:58:21
【问题描述】:
<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);
    });

我想知道如何以及在哪里指定 这个 angularjs 发布请求中的内容类型:multipart/form-data?

请帮忙。 默认似乎是“应用程序/json,文本/纯文本” 这不适用于图像/文件上传。

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

上面的代码总是回显不成功。

【问题讨论】:

    标签: javascript angularjs http post content-type


    【解决方案1】:

    $http.post Angular 中的快捷方法采用三个参数,url、请求数据和一个配置对象,您可以在其中设置如下标头:

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

    你的情况是:

    $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);
    });
    

    你也可以像下面这样构造请求对象:

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

    然后像这样发出请求:

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

    如果您想设置通用的应用程序范围的标头,您可以使用默认标头,默认情况下将添加到所有请求中,如下所示:

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

    这将为所有请求添加上述内容类型。

    更多信息在文档here

    【讨论】:

    • Content-Type 中的“-”是抛出错误。意外的令牌。
    • 也尝试了第二个选项“$http(req)”,但它只是没有显示在 php 服务器上。当我尝试这个 if(isset($_FILES['articleimg'])===true ){ echo "sucessfull"; }else echo "不成功";
    • 添加引号确实消除了错误。谢谢。但服务器端没有锁。
    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2013-10-27
    • 1970-01-01
    • 2017-11-13
    • 2018-01-21
    相关资源
    最近更新 更多