如何使用AngularJS-Backend:PHP使用表单上传图像


How to use a form to upload a image with AngularJS - Backend: PHP

我是AngularJS的新手,我想创建一个表单,用户可以在其中注册车辆信息(车主、型号、描述、照片)。我上传照片时遇到问题,不知道是否有人能帮我。谢谢!

HTML

<div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" ng-click="close('Cancel')" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Add new Vehicle...</h4>
            </div>
            <div class="modal-body">
                <form ng-submit="newVehicle()" name="newVehicleForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="owner">Owner</label>
                        <input type="text" name="owner" class="form-control" placeholder="owner" ng-model="newVehicleForm.belongsto" >
                        <br />
                        <label for="description">Description</label><br />
                        <textarea class="form-control" name="description" placeholder="description"  ng-model="newVehicleForm.description" cols="50" rows="5"></textarea>
                        <br />
                        <label for="vehiclebrand">Brand</label>
                        <select name="vehiclebrand" class="form-control" ng-model="newVehicleForm.brandtitle" ng-change="getVehicleModelsThenAvailable(newVehicleForm.brandtitle)" ng-options="vehicle_brand.brandtitle as vehicle_brand.brandtitle for vehicle_brand in vehicle_brands" ></select>
                        <br />
                        <label for="vehiclemodel">Model</label>
                        <select name="vehiclemodel" class="form-control" ng-model="newVehicleForm.modeltitle" ng-options="vehicle_brand_model.modeltitle as vehicle_brand_model.modeltitle for vehicle_brand_model in vehicle_brand_models" ></select>
                        <br />
                        <label for="image">Photo</label>
                        <input type="file" name="image" name="fileToUpload" id="fileToUpload" file-model="myFile" accept="image/*" />
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" ng-click="close('No')" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" ng-click="newVehicle()" class="btn btn-success" data-dismiss="modal">Add</button>
            </div>
        </div>

角度控制器-->vehicleCtrl.js

        app.controller('vehiclesCtrl', ['$scope', 'vehiclesService', 'ModalService', function($scope, vehiclesService, ModalService){
        $scope.newVehicle = function () {
            //file to upload
            var file = $scope.myFile;
            console.log('file is ' );
            console.dir(file);
            vehiclesService.uploadFileToUrl(file);
            //other form inputs
            var newVehicleDataObject = $scope.newVehicleForm;
            vehiclesService.createNewVehicle(newVehicleDataObject)
                .success(function () {
                })
                .error(function (error) {
                    $scope.status = 'Unable to insert vehicle: ' + error.message;
                });
        }
}]);

角度服务-->vehiclesService.js

app.factory('vehiclesService',['$http',
     function ($http) {
      var urlBase = 'data/';
      var vehiclesService = {};
vehiclesService.createNewVehicle = function (newVehicleDataObject) {
          return $http.post(urlBase + 'vehicles/createNewVehicle.php', JSON.stringify(newVehicleDataObject));
      }; 
vehiclesService.uploadFileToUrl = function(file){
          var fd = new FormData();
          fd.append('file', file);
          fd.append('name', name);
          return $http.post(urlBase + 'vehicles/uploadFile2.php', fd);
       }
      return vehiclesService;
  }]);

最后,我的PHP后端代码uploadFile2.PHP

<?php
$target_dir = "";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

我没有收到任何PHP和JavaScript错误,但图像也没有上传。

但是,如果我简单地使用下面的基本HTML方法和上面的PHP代码,文件就会上传。

<form action="data/vehicles/uploadFile2.php" method="post" enctype="multipart/form-data">
           Select image to upload:
            <input type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload Image" name="submit">
</form>

那么,我的问题可能是在控制器或表单中的某个地方,我不知道。基本上,与我在ng model="newVehicleForm.variable"中传输文本输入数据的方式相同,我也想知道通过ng model或类似的方式传输文件的方法。请帮我解决问题。

非常感谢!

大家好!由于存在多个问题,我设法找到了解决方案。

问题1:正如您所看到的,在我的HTML代码中,我有两个属性"name"。我不确定这是否至关重要,但这绝对不是一个好的做法。

问题2:在我的vehiclesService.js中,我丢失了一些代码,以便告诉PHP脚本所需的文件格式数据。

问题#3:在我的PHP脚本中,我将文件的变量命名为"fileToUpload"。但在vehiclesService.js中,我将其命名为"file",因此这里存在最大的问题。

接下来我将发布所有的最终工作代码。有任何疑问,只要问我,我希望我能帮上忙。

HTML

<div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" ng-click="close('Cancel')" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Add new Vehicle...</h4>
            </div>
            <div class="modal-body">
                <form ng-submit="newVehicle()" name="newVehicleForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" name="name" class="form-control" placeholder="name" ng-model="newVehicleForm.name" >
                        <br />
                        <label for="owner">Owner</label>
                        <input type="text" name="owner" class="form-control" placeholder="owner" ng-model="newVehicleForm.belongsto" >
                        <br />
                        <label for="platenumber">Platenumber</label>
                        <input type="text" name="platenumber" class="form-control" placeholder="platenumber" ng-model="newVehicleForm.platenumber" >
                        <br />
                        <label for="description">Description</label><br />
                        <textarea class="form-control" name="description" placeholder="description"  ng-model="newVehicleForm.description" cols="50" rows="5"></textarea>
                        <br />
                        <label for="vehiclebrand">Brand</label>
                        <select name="vehiclebrand" class="form-control" ng-model="newVehicleForm.brandtitle" ng-change="getVehicleModelsThenAvailable(newVehicleForm.brandtitle)" ng-options="vehicle_brand.brandtitle as vehicle_brand.brandtitle for vehicle_brand in vehicle_brands" ></select>
                        <br />
                        <label for="vehiclemodel">Model</label>
                        <select name="vehiclemodel" class="form-control" ng-model="newVehicleForm.modeltitle" ng-options="vehicle_brand_model.modeltitle as vehicle_brand_model.modeltitle for vehicle_brand_model in vehicle_brand_models" ></select>
                        <br />
                        <label for="vehicletype">Type</label>
                        <select name="vehicletype" class="form-control" ng-model="newVehicleForm.title" ng-options="vehicle_type.title as vehicle_type.title for vehicle_type in vehicle_types" ></select>
                        <br />
                        <label for="image">Photo</label>
                        <input type="file" name="image" id="fileToUpload" file-model="myFile" accept="image/*" />
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" ng-click="close('No')" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" ng-click="newVehicle()" class="btn btn-success" data-dismiss="modal">Add</button>
            </div>
        </div>

角度控制器-->vehicleCtrl.js

'use strict';
app.controller('vehiclesCtrl', ['$scope', 'vehiclesService', 'ModalService', function($scope, vehiclesService, ModalService){
$scope.newVehicle = function () {
        //file to upload
        var file = $scope.myFile;
        console.log('file is ' );
        console.dir(file);
        vehiclesService.uploadFileToUrl(file);
        //other form inputs
        var newVehicleDataObject = $scope.newVehicleForm;
        vehiclesService.createNewVehicle(newVehicleDataObject)
            .success(function () {
            })
            .error(function (error) {
                $scope.status = 'Unable to insert vehicle: ' + error.message;
            });
    }
}]);

角度服务-->车辆服务.js

'use strict';
app.factory('vehiclesService',
    ['$http',
     function ($http) {
      var urlBase = 'data/';
      var vehiclesService = {};
vehiclesService.createNewVehicle = function (newVehicleDataObject) {
          return $http.post(urlBase + 'vehicles/createNewVehicle.php', JSON.stringify(newVehicleDataObject));
      }; 
        //file upload service
      vehiclesService.uploadFileToUrl = function(file){
           var fd = new FormData();
           fd.append('file', file);
           console.log (file);
           $http.post(urlBase + 'vehicles/uploadFile2.php', fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            })
                  .success(function(){})
                  .error(function(){});
            }
      return vehiclesService;
  }]);

上传文件2.php

<?php
$target_dir = "";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

我的解决方案基于此链接中的代码。