【问题标题】:How to use a form to upload a image with AngularJS - Backend: PHP如何使用表单通过 AngularJS 上传图像 - 后端:PHP
【发布时间】:2016-03-26 23:39:08
【问题描述】:

我是 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>

Angular 控制器 --> 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;
                });
        }
}]);

Angular 服务 --> 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 或类似方式传输文件的方式。 请帮我解决一下。

非常感谢!

【问题讨论】:

    标签: javascript php angularjs forms file-upload


    【解决方案1】:

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

    问题 #1: 如您所见,在我的 HTML 代码中,我有两个属性“名称”。我不确定这是否至关重要,但绝对不是一个好习惯。

    问题 #2: 在我的 vehiclesService.js 中我遗漏了一些代码,以便告诉 PHP 脚本预期的文件格式数据。

    问题 #3: 在我的 PHP 脚本中,我将文件的变量命名为“fileToUpload”。但是在 vehiclesService.js 中,我将其命名为“文件”,所以这里有最大的问题。

    接下来我将发布所有最终工作代码。有任何疑问,尽管问我,希望我能提供帮助。

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

    Angular 服务 --> VehicleService.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.";
        }
    }
    ?>
    

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

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 2018-11-11
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2021-01-18
      • 2016-07-09
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多