Skip to content

Instantly share code, notes, and snippets.

@gausam
Created January 12, 2014 10:37
Show Gist options
  • Save gausam/c8a4ef560dd7b3a43337 to your computer and use it in GitHub Desktop.
Save gausam/c8a4ef560dd7b3a43337 to your computer and use it in GitHub Desktop.
Very simple file uploading in AngularJS no plugins (dirty, but works)
var myApp = angular.module('AppLoad', []);
myApp.factory('formDataObject', function(){
return function(data, headersGetter){
var fd = new FormData();
angular.forEach(data, function(value, key){
fd.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return fd;
};
});
myApp.directive('file', function(){
return {
scope: {
file: '='
},
link: function(scope, el, attrs){
el.bind('change', function(event){
var files = event.target.files;
var file = files[0];
scope.file = file ? file.name : undefined;
scope.$apply();
});
}
};
});
myApp.controller('ipapo', function($scope, $http, formDataObject){
$scope.sam = 'yes';
$scope.musvo = {
f1 : 'frst',
f2 : 'second',
file1: ''
};
$scope.potsera = function(){
$scope.msg = '';
var req = new FormData();
file_input_element_id = "file1";
file_input_data_key = "file1";
for (var key in $scope.musvo) {
if ($scope.musvo.hasOwnProperty(key)) {
if (key != file_input_data_key) {
console.log(key + " -> " + $scope.musvo[key]);
req.append(key, $scope.musvo[key]);
}
else{
console.log('Skipped: ' + key + " -> " + $scope.musvo[key]);
}
}
}
var el = document.getElementById(file_input_element_id);
req.append(file_input_data_key, el.files[0]);
$http.post('http://localhost/pipe/ae/test', req, {
'Content-Type': undefined,
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
delete headers['Content-Type'];
return data;
}
})
.success(function(data, status, headers, config){
$scope.msg = 'all vent vell';
})
.error(function(data, status, headers, config){
$scope.msg = 'was an error';
});
/*
http://badwing.com/multipart-form-data-ajax-uploads-with-angularjs/
http://stackoverflow.com/questions/19411848/angularjs-ajax-post-form-with-file-upload
http://stackoverflow.com/questions/684672/loop-through-javascript-object
https://groups.google.com/forum/#!topic/angular/MBf8qvBpuVE
REF http://jasonturim.wordpress.com/2013/09/12/angularjs-native-multi-file-upload-with-progress/
*/
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment