Skip to content

Instantly share code, notes, and snippets.

@dpogorzelski
Created August 22, 2013 15:48
Show Gist options
  • Save dpogorzelski/6308988 to your computer and use it in GitHub Desktop.
Save dpogorzelski/6308988 to your computer and use it in GitHub Desktop.
Simplified version of "angular-file-upload" directive. Removed support for old browsers. (original version: https://github.com/danialfarid/angular-file-upload)
"use strict";
app.controller('mainCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.onFileSelect = function(files) {
console.log(files);
for (var i = 0; i < files.length; i++) {
var file = files[i];
$http.uploadFile({
url: 'api/file',
file: file
})
}
}
}
]);
"use strict";
var directives = angular.module('myapp.directives', []);
directives.directive('ngFileSelect', ['$parse', '$http',
function($parse, $http) {
if ($http.uploadFile === undefined) {
$http.uploadFile = function(config) {
console.log(config)
return $http({
method: 'POST',
url: config.url,
headers: {
'Content-Type': false
},
transformRequest: function(data) {
var formData = new FormData();
formData.append('file', config.file);
return formData;
}
});
};
}
return function(scope, elem, attr) {
var fn = $parse(attr['ngFileSelect']);
elem.bind('change', function(evt) {
var files = [];
var fileList = evt.target.files;
for (var i = 0; i < fileList.length; i++) {
files.push(fileList.item(i));
}
scope.$apply(function() {
fn(scope, {
files: files,
$event: evt
});
});
});
};
}
]);
<input type="file" ng-file-select="onFileSelect(files)" multiple>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment