编程语言
首页 > 编程语言> > javascript – 如何使用FormData API发出POST请求

javascript – 如何使用FormData API发出POST请求

作者:互联网

我想使用http.post将username和form_data对象传递给php文件
当我只传递form_data时它会上传我的图片.但我想传递一些其他信息,如用户名.请帮我如何传递http.post中的其他数据
这是我的php文件.

<?php include "connectdb.php";
    $data=json_decode(file_get_contents("php://input"));
    $name=$dbhandle->real_escape_string($data->susername);
    if (!empty($_FILES)) {
        $date=2;
        $path = 'fooditem/'. $_FILES['file']['name'];
        if (move_uploaded_file($_FILES['file']['tmp_name'],$path)) {
           $query="INSERT INTO `login`(`id`,`type`,`img`) VALUES('".$name."','".$date."','".$_FILES['file']['name']."')";   
           if($dbhandle->query($query)){
               echo 'File Uploaded';
           }
           else
               echo 'File Uploaded But Not Saved';
        }
    }else{
     echo 'Some Error';
    }
myapp.directive("fileInput",function($parse){
   return{
       link: function($scope,element,attrs){
           element.on("change",function(event){
               var files = event.target.files;
               $parse(attrs.fileInput).assign($scope, element[0].files);
               $scope.$apply();
               // console.log(files[0].name);
           });
       }
   } 
});
myapp.controller("myController",function($scope,$http){        
    $scope.signup = function(){

    var form_data = new FormData();
        angular.forEach($scope.files,function(file){
            form_data.append('file',file);
        });
    $http.post("picupload.php",{'susername':$scope.susername,form_data})
      .then(function(response){
          console.log(response);
    })                
});        
<input type="text" ng-model="username" name="username">
<input type="file" file-input="files" accept="image/*" />
<input type="submit" value="SIGN UP" ng-click="signup()"
       name="signup_btn" class="btn btn-primary">

解决方法:

你可以添加这样的东西:

 myapp.controller("myController",function($scope,$http){
        $scope.signup = function(){    
        var form_data = new FormData();
        angular.forEach($scope.files,function(file){
                form_data.append('file',file);
        });
        form_data.append('susername',$scope.susername);  // new line
        var config = {headers: { 'Content-type': undefined } };
        $http.post("picupload.php",form_data, config)
                .success(function(response){
                alert(response);
        });                
}   

我不确定PHP,但谷歌搜索后我发现在php’susername’可以检索如下:

$_POST['susername'];

标签:javascript,php,angularjs,form-data,angularjs-fileupload
来源: https://codeday.me/bug/20190923/1814288.html