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.
Steve TinsleyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ioannis ParaskevopoulosCommented:
Hi,

$http.post is a promise, so you may append a 'then' after it:

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 }
        }).then(function(response){
            //success code here 
        },function(response){
            //failure code here 
        });
    }
}])

Open in new window


Giannis
Steve TinsleyAuthor Commented:
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....
Ioannis ParaskevopoulosCommented:
To be honest  i have not worked with files, so i cannot really comment.

Giannis
tr0gd0rCommented:
@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.
BigRatCommented:
One doesn't do this sort of thing by omeself, but uses a module prepared by somebody else. That is Angular's strength. In this link there is a list of modules you can use

stackoverflow.com/questions/18571001/file-upload-using-angularjs

and here is just one of them : http://ngmodules.org/modules/ng-file-upload which handles progress, cancel/abort and even drag and drop. Trying to do this yourself because as a beginner is almost impossible to get this sort of functionality implemented by yourself. Try searching for the functionality you require and install and use it.

I notice the way in which you app is defined. If you stick to conventions like here :

https://github.com/johnpapa/angular-styleguide#style-y030

you'll find it easier to produce the code and maintain it. You'll also find it much easier to integrate other peoples modules.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Angular

From novice to tech pro — start learning today.