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:
I have no idea why because I can get the content in my logs. console.log:
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); }) } } });
select-ng-files
directive from my answer in ng-model for<input type=“file”/>
(with directive DEMO). It binds a FileList object to theng-model
directive.FileList
is an array-like object not aFile
object.