Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cirovladimir/acd426079614a5f6ef6ed03bc2b71b14 to your computer and use it in GitHub Desktop.
Save cirovladimir/acd426079614a5f6ef6ed03bc2b71b14 to your computer and use it in GitHub Desktop.
angular js bootstrap 3.3.7 file upload button, directive and controller
//************* view ***********//
<div class="pull-right">
<label class="btn btn-primary">
<span class="glyphicon glyphicon-upload"></span>
<span>Importar...</span>
<input type="file" class="hidden" file-on-change="vm.uploadfile"></label>
</div>
//************* controller ***********//
function uploadfile(event){
if(event.target.files && event.target.files.length > 0){
console.log('uploading file...', event.target.files);
var fd = new FormData();
fd.append('filePadron', event.target.files[0]);
$http.post('api/padron/import',fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function () {
console.log('files uploaded successfully');
$state.reload();
}).error(function (error) {
console.log('error: couldnt upload files', error);
alert('Ocurrió un error al importar el archivo: ' + error.title);
});
}
}
//************* directive ***********//
(function () {
'use strict';
angular
.module('reportesApp')
.directive('fileOnChange', fileOnChange);
function fileOnChange() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var onChangeHandler = scope.$eval(attrs.fileOnChange);
element.on('change', onChangeHandler);
element.on('$destroy', function () {
element.off();
});
// clear value after change handler fired to allow uploading the same file again (i.e. change is fired again)
element.on('click', function () {
element.val('');
});
}
};
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment