We help IT Professionals succeed at work.
Get Started

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

Last Modified: 2015-08-29
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;

    $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(){
                    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.
Watch Question
This problem has been solved!
Unlock 2 Answers and 5 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE