Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Last active August 29, 2015 14:06
Show Gist options
  • Save fmtarif/862530970381a772855a to your computer and use it in GitHub Desktop.
Save fmtarif/862530970381a772855a to your computer and use it in GitHub Desktop.
#ng angular file upload using HTML 5 File API
<!DOCTYPE html>
<html>
<!--From: http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs -->
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
/** an alternative from: http://plnkr.co/edit/xLM9VX?p=preview
* @TODO - test and update this gist
myApp.directive('fileSelect', function() {
var template = '<input type="file" name="files"/>';
return function( scope, elem, attrs ) {
var selector = $( template );
elem.append(selector);
selector.bind('change', function( event ) {
scope.$apply(function() {
scope[ attrs.fileSelect ] = event.originalEvent.target.files;
});
});
scope.$watch(attrs.fileSelect, function(file) {
selector.val(file);
});
};
});
to clear the file field do the following in controller
$scope.file = null;
*/
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(res) {
console.log(res);
})
.error(function() {
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "upload.php";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</body>
</html>
<?php
print_r($_FILES);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment