Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
myApp.directive('ngFileModel', ['$parse', function ($parse) {
// return {
// restrict: 'A',
// link: function(scope, element, attrs) {
// var model = $parse(attrs.ngFileModel);
// var modelSetter = model.assign;
// element.bind('change', function(){
// scope.$apply(function(){
// modelSetter(scope, element[0].files[0]);
// });
// });
// }
// };
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var modelSetter = model.assign;
var isMultiple = attrs.multiple;
element.bind('change', function() {
var values = [];
angular.forEach(element[0].files, function(item) {
values.push(item);
});
scope.$apply(function() {
// console.log('here');
if(isMultiple) {
// console.log('values:', values);
modelSetter(scope, values);
} else {
// console.log('value ', values);
modelSetter(scope, values[0]);
}
});
});
}
}
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(files, uploadUrl){
var fd = new FormData();
fd.append('logo', files);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(res){
console.log('success', res);
})
.error(function(res){
console.log('error', res);
});
}
}]);
myApp.controller('UploadFileController',['$scope', '$http', 'fileUpload', function($scope, $http, fileUpload) {
$scope.files = [];
$scope.uploadFile = function(){
var uploadUrl = "http://localhost:3003/fileUpload";
fileUpload.uploadFileToUrl($scope.files, uploadUrl);
}
// $scope.uploadFile = function() {
// var uploadUrl = "http://localhost:3003/fileUpload";
// fileUpload.uploadFileToUrl($scope.files, uploadUrl);
// }
}]);
<div class="container-fluid">
<div class="row form-group">
<input type="file" ng-file-model="files" multiple />
</div>
<!-- <div class="row form-group">
<input type = "file" file-model="files" name="files" multiple/>
</div> -->
<div class="row form-group">
<button class="btn btn-success col-2 col-sm-2 offset-sm-1" ng-click='uploadFile()'>Upload</button>
</div>
<div class="row form-group">
<p ng-repeat="file in files">
{{file.name}}
</p>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.