Skip to content

Instantly share code, notes, and snippets.

@definitelynotsoftware
Last active December 13, 2019 21:52
Show Gist options
  • Save definitelynotsoftware/80ea3469c6c520dbdc2e to your computer and use it in GitHub Desktop.
Save definitelynotsoftware/80ea3469c6c520dbdc2e to your computer and use it in GitHub Desktop.
AngularJS HTML5 File Upload
...
// using an explicit call to $scope to reference from the input type='file' onchange event.
// Also, using $scope to manually call $apply when 'attachmentList' changes - see addAttachment()
$scope.addAttachment = addAttachment;
var vm = this;
vm.removeAttachment = removeAttachment;
vm.attachmentList = [];
vm.attachment = {};
vm.attachmentListCount = 0;
var files = [];
function removeAttachment(attachment) {
log('removing attachment: ' + attachment.FileName);
vm.attachmentList.splice(vm.attachmentList.indexOf(attachment), 1);
vm.attachmentListCount = vm.attachmentList.length;
}
function addAttachment(evt) {
files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
$scope.$apply(function () {
vm.attachment = {
FileAsString: e.target.result,
FileName: theFile.name
};
vm.attachmentList.push(vm.attachment);
vm.attachmentListCount = vm.attachmentList.length;
});
};
})(f);
// FileReader
reader.readAsDataURL(f);
}
}
<input class="text-subtle" accept="application/pdf, text/*, image/*" onchange='angular.element(this).scope().addAttachment(window.event)' type="file" multiple style="width: 100px;" />
<span>{{vm.attachmentListCount}}</span> file(s)
<ul>
<li style="list-style: none;" data-ng-repeat="a in vm.attachmentList">
<i class="fa fa-file"></i>&nbsp;&nbsp;{{a.FileName}}
<a data-ng-click="vm.removeAttachment(a)" class="text-removeQuote">remove</a>
</li>
</ul>
app.directive('fileUpload', function () {
return {
restrict: 'E',
templateUrl: 'app/directives/file-upload.html'
};
});
<fieldset>
<legend>Attachments</legend>
<file-upload></file-upload>
</fieldset>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment