Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm new with AngularJS and I want to create a form where a user can register a vehicle information (owner, model, description, photo). I am having trouble uploading the photo and I wonder if anyone can help me. Thank you!

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 Controller --> 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 Service --> 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;

  }]);

Finally, my PHP backend code 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.";
    }
}
?>

I don't receive any PHP and JavaScript error, but the image is not uploaded also.

However, if I simply use the following basic HTML method with the PHP code above, the file is uploaded.

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

Then, my problem is perhaps somewhere in the Controller or in the form, I don't know. Basically, the same way I transport data inside ng-model="newVehicleForm.variable" for the text inputs, I want to know also a way to transport the file through ng-model's or similar. Please, help me with a solution.

Many thanks!

share|improve this question
up vote 0 down vote accepted

Good news, everyone! I managed to find the solution due to multiple problems.

Problem #1: as you can see, in my HTML code I had two attributes "name". I'm not sure it was crucial, but definitively it's not a good practice.

Problem #2: in my vehiclesService.js I was missing some code in order to tell the PHP script the expected file format data.

Problem #3: in my PHP script, I named the variable of the file as "fileToUpload". But in vehiclesService.js I named it as 'file', so there was here the biggest problem.

I'm posting next all the final working code. Any doubt, just ask me and I hope I can help.

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>

Angular Controller --> 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 Service --> vehiclesService.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;

  }]);

uploadFile2.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.";
    }
}
?>

I based my solution in the code disposed in this link.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.