Reputation: 4811
I am trying to add multiple files into a file array and later on access the each files in AngularJs.So far i have created a custom directive to read files looking at some posts.it was working fine with a single file.But my requirement is that i want to upload multiple files and add them into array and later on access the created file array when accessing the data.I am newbie to AngularJs please help me to achieve this.
HTML code snippet
<div class="input input-file ">
<span class="button"><input on-read-file="readFileContent($fileContent)"
type="file" id="attachments" name="file" data-ng-model="attachments"
onchange="this.parentNode.nextSibling.value = this.value">Browse</span>
<input type="text" placeholder="Attach some files" readonly="">
</div>
Custom directive for read input files
var mimeType,fileName;
testModule.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
//Get the Uploaded file mime type
mimeType=(onChangeEvent.srcElement || onChangeEvent.target).files[0].type;
fileName=(onChangeEvent.srcElement || onChangeEvent.target).files[0].name;
});
}
};
});
Read File Content Method
$scope.readFileContent = function($fileContent){
$scope.content = $fileContent;
};
Upvotes: 3
Views: 7866
Reputation: 17647
I suggest to check this post on StackOverflow:
Upload multiple files in angular
One of the answers contains this working example:
http://plnkr.co/edit/B13t84j5IPzINMh1F862?p=preview
It uses a directive named ng-file-model:
<input type="file" ng-file-model="files" multiple />
Upvotes: 1