使用Angular JS和php上传文件和表单

时间:2017-04-28 04:17:16

标签: php angularjs

我有一个表单,并且我有要上传的文件。 我已经成功地单独完成了这项工作,但我不知道如何一键完成。 请帮忙。

这是我的指示

var postApp = angular.module('postApp', []);
    postApp.directive("fileInput", function($parse){  
        return{  
            link: function($scope, element, attrs){  
                element.on("change", function(event){  
                    var files = event.target.files;  
                    //console.log(files[0].name);  
                    $parse(attrs.fileInput).assign($scope, element[0].files);  
                    $scope.$apply();  
                });  
            }  
        }  
    });

这是我的控制器

postApp.controller('postController', function($scope, $http) {

        $scope.submitForm = function() {
        var form_data = new FormData();  
           angular.forEach($scope.files, function(file){  
                form_data.append('file', file);  
          'Nama_Usaha':$scope.Nama_Usaha              
        $http.post("db/form_daftarAct.php", form_data, 
        {
            transformRequest: angular.identity,  
                headers: {'Content-Type': undefined,'Process-Data': false}

          })
          .success(function(data) {
              // console.log(data);
          });
        };
    });

这是我的表格

<body ng-app="postApp" ng-controller="postController">
  <form> 
    <input ng-model="Nama_Usaha">
    <input multiple type="file" file-input="files"/>
    <input type="text"ng-model="Operasional" >
    <textarea ng-model="Keterangan" ></textarea>
  <button type="submit" ng-click="submitForm()>Submit</button>
  </form>
</body>

这是我的form_daftarAct.php

    <?php
    $data = json_decode(file_get_contents("php://input"));

    //get data from object
    $nama=$data->Nama_Usaha;

    $query= "INSERT INTO `tempat_sehat` (`id_tempat_sehat`, `nama_tempat_sehat`) VALUES (null,'$nama')";

//insert the form
    $input = mysqli_query($connect, $query);

//get the id
    $getnewid = mysqli_query($connect,"SELECT * FROM `tempat_sehat` WHERE `nama_tempat_sehat`='$nama'");

    $col=mysqli_fetch_array($getnewid); 
    $id=$col['id_tempat_sehat'];

// here is uploaded file using php
     if(!empty($_FILES))  
     {  
          $path = 'upload/' . $_FILES['file']['name'];  
          if(move_uploaded_file($_FILES['file']['tmp_name'], $path))  
          {
               $query3 = "INSERT INTO `foto`(`foto`, `id`) VALUES ('$_FILES['file']['name']', '$id')";  
               if(mysqli_query($connect, $query3))  
               {  
                    echo 'File Uploaded';  
               }  
          }  

     }
    ?>

0 个答案:

没有答案