0

I am doing a file upload in angularjs. I am unable to get the file object content before sending to my back-end. XHR, headers:

XHR-Header

I have no idea why because I can get the content in my logs. console.log:

logs

These are my codes: html:

<body ng-app="myApp" ng-controller="appCtrl">
     <input type="file" id="file" name="files" accept="text/*" 
            data-url="file" class="inputfile_upload" select-ng-files
            ng-model="uploadedFile"/>
     <label for="file"> <span id="chooseFile"></span>Upload a file!</label>
     <button id="submitBtn" type="submit" ng-click="upload()">Upload</button>
</body>

controller.js:

var app = angular.module('myApp', [])
app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){

    $scope.upload = function() {
       var file = $scope.uploadedFile; 
       console.log('file is ' );
       console.dir(file);

       var uploadUrl = "/uploaded_file";
       fileUploadService.uploadFileToUrl(file, uploadUrl);
    };
}

service.js:

app.factory('fileUploadService', function ($rootScope, $http) {
    var service = {};
    service.uploadFileToUrl = function upload(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function successCallback(response){
            console.log("Files added");
        }, function errorCallback(response){
            console.log("Files not successfully added");
        })    
    }
    return service;
});

directive.js:

app.directive("selectNgFiles", function($parse) {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
5
  • This looks like the same code as this question by @user3774763. Are you using two accounts to post questions? Commented Jan 3, 2020 at 7:34
  • You are using my select-ng-files directive from my answer in ng-model for <input type=“file”/> (with directive DEMO). It binds a FileList object to the ng-model directive. FileList is an array-like object not a File object. Commented Jan 3, 2020 at 7:51
  • 1
    Does this answer your question? AngularJS Unable to display upload file logs Commented Jan 3, 2020 at 7:53
  • @georgeawg can you explain further, like what else do I need to do? Commented Jan 3, 2020 at 7:56
  • @AshishBakwad no, the controller codes are the same Commented Jan 3, 2020 at 7:56

0