Để upload file trong angularjs cần viết directive
app.directive('photoFile', function($parse){
return {
restrict: 'A',
link : function(scope, element, attributes){
var set = $parse(attributes.photoFile);
element.bind('change', function(){
set.assign(scope, element[0].files);
scope.$apply();
})
}
}
});
Up nhiều file
app.directive('attachmentFile', function($parse){
return {
restrict: 'A',
link : function(scope, element, attributes){
var model = $parse(attributes.attachmentFile);
var assign = model.assign;
element.bind('change', function(){
var files = [];
angular.forEach(element[0].files, function(file){
files.push(file);
});
scope.$apply(function(){
assign(scope, files);
});
// model.assign(scope, element[0].files);
// scope.$apply();
});
}
}
});
Trong hàm upload file
$scope.createEmployee = function(){
var form = $scope.empfrm;
var fd = new FormData();
fd.append('name', form.name);
fd.append('description', form.description);
fd.append('photo', form.photo_file[0]);
angular.forEach(form.attachment_files, function(file, key){
var filename = 'attached_file'+key;
fd.append(filename, file);
});
// call sevice
EmployeeHttpService.saveMultipartFormData('/admin/product/category/add', fd, function(response){
$location.path('/product/category');
// $scope.showSimpleToast('Thêm thành công !')
toaster.pop('success', "Thêm thành công !", '', 5000, 'trustedHtml');
})
}
Sử dụng directive trong html
<div class="col-sm-5">
<div class="form-group">
<label for="">Ảnh đại diện</label>
<input type="file" name="image" class="form-control" photo-file="empfrm.photo_file"
onchange="angular.element(this).scope().previewPhoto(event)"
>
<div class="mrow">
<img style="width: 180px; height: 150px; text-align: center;" class="img-
thumbnail" src="" alt="" ng-src="{{ photo }}"/>
</div>
</div>
<div class="form-group">
<label for="">Hình kèm theo</label>
<input id="attachments" type="file" attachment-file="empfrm.attachment_files"
onchange="angular.element(this).scope().previewAttachments(event)" multiple />
<div class="mrow">
<ul style="padding-left: 20px;">
<li class="attachment_list" ng-repeat="attachment in attachments">
{{ attachment }}
</li>
</ul>
</div>
</div>
</div>