Skip to content

Instantly share code, notes, and snippets.

@busticated
Last active December 19, 2015 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save busticated/6004953 to your computer and use it in GitHub Desktop.
Save busticated/6004953 to your computer and use it in GitHub Desktop.
app.factory('fileUpload', function($q){
return {
send: function(files){
var deferred = $q.defer(),
data = new FormData(),
xhr = new XMLHttpRequest();
angular.forEach(files, function(file){
data.append('file', file, file.name);
});
console.log('sending file data');
xhr.open('POST', '/upload');
xhr.onload = function(event){ deferred.resolve(event); console.log('on load fired'); };
xhr.onerror = function(event){ deferred.reject(event); console.log('on error fired'); };
xhr.send(data);
return deferred.promise;
}
};
});
app.directive('imageUpload', function($dialog){
return {
scope: {},
restrict: 'A',
controller: function($scope, $dialog){
var dialogOptions = {
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '/html/tmpl.dialog.addimg.html',
controller: function($scope, dialog, fileUpload){
$scope.selectedFiles = null;
$scope.selectFiles = function(files){
console.dir(files);
$scope.selectedFiles = files;
};
$scope.close = function(){
console.log('cancel');
$scope.selectedFiles = null;
dialog.close();
};
$scope.submit = function(){
var onSuccess = function (e) {
console.log('post completed');
console.dir(e);
dialog.close();
},
onError = function (event) {
console.log('post fail');
dialog.close();
};
fileUpload.send($scope.selectedFiles)
.then(onSuccess, onError);
};
}
};
$scope.open = function(){
$dialog
.dialog(dialogOptions)
.open();
};
},
link: function(scope, elem, attrs){
}
}
});
<button image-upload ng-click="open()" class="btn"><i class="icon-upload"></i> Upload Image</button>
<form ng-submit="submit()" class="modal-form" enctype="multipart/form-data">
<div class="modal-header">
<button ng-click="close()" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Upload Images</h3>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="control-group">
<label class="control-label" for="images">Images</label>
<div class="controls">
<input type="file" name="images" multiple onchange="angular.element(this).scope().selectFiles(this.files)"/>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment