Link to home
Start Free TrialLog in
Avatar of Steve Tinsley
Steve TinsleyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Angularjs form and file upload - how to get success or error

I want to create a form to upload name and a file.
I have managed to get it working, but not sure how to get success / error...

here is the code which works:

var app = angular.module('app', ['onsen', 'ngRoute']);

app.controller('page1', ['$scope', 'multipartForm', function($scope, multipartForm){
    console.log("Page 1 Controller");
    $scope.title = "Welcome";

    $scope.file_changed = function(element) {
        var photofile = element.files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            $scope.$apply(function() {
                $scope.prev_img = e.target.result;
            });
        };
        reader.readAsDataURL(photofile);
    };

    $scope.form = {};
    $scope.Submit = function(){
        var uploadUrl = 'api/process2.php';
        multipartForm.post(uploadUrl, $scope.form);
    }
}]);

app.directive('fileModel', ['$parse', function($parse){
    return {
        restrict: 'A',
        link: function(scope, element, attrs){
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                })
            })
        }
    }
}])



app.service('multipartForm', ['$http', function($http){
    this.post = function(uploadUrl, data){
        var fd = new FormData();
        for(var key in data)
            fd.append(key, data[key]);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.indentity,
            headers: { 'Content-Type': undefined }
        });
    }
}])

Open in new window



Ideally i would like to add a progress bar to this aswell... but I dont know how.
SOLUTION
Avatar of Ioannis Paraskevopoulos
Ioannis Paraskevopoulos
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Steve Tinsley

ASKER

Hi,

Thanks for the pointers. I understand now.

Do you think that this is the best way for doing this form/image upload.

I am slowly learning this....
To be honest  i have not worked with files, so i cannot really comment.

Giannis
Avatar of tr0gd0r
tr0gd0r

@sjtinsley83, this method of form input works well for relatively small files. If you need to support large files (over 10MB) you may want to consider a library that can send the file data in chunks and provide you with progress events that will allow you to display a progress bar.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial