How to make POST requests with the FormData API

旧城冷巷雨未停 提交于 2019-12-17 05:15:12

问题


I want to pass the username and form_data object to the php file using http.post when i pass only form_data it works my picture upload. but i want to pass some other information like username as well. please help me how to pass other data in http.post And here is my php file.

<?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">

回答1:


You can add something like this:

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

I'm not sure about PHP but after googling I found that in php 'susername' can retrieved as below:

$_POST['susername'];



回答2:


How to make POST requests with the FormData API

When posting objects created by the FormData API, it is important to set the Content-type header to undefined.

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

    var config = {headers: { 'Content-type': undefined } };

    return $http.post("picupload.php",form_data, config)
      .then(function(response){
        console.log(response.data);
        return response.data;
    });                
};

Also a FormData object can not be serialized into a JSON string it must be sent by the XHR API alone. Append all necessary data to the FormData object.

When the XHR send API posts an object created by the FormData API, it automatically sets the content type header to multipart/form-data with a proper encapsulation boundary and encodes the data using base64 encoding.

Normally the $http service overrides the XHR API sets the content type header to application/json. Setting the content type header to undefined allows the XHR API the freedom to set the header properly.


Update

On the server side use:

$_POST['susername'];

to receive the data item.



来源:https://stackoverflow.com/questions/43454986/how-to-make-post-requests-with-the-formdata-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!