VANHIEP.NET - Làm web giá rẻ - Thiết Kế Website - Thiết Kế Ứng Dụng Mobile

upload one file and multi file in angularjs

Để 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

 

                      

                        Ảnh đại diện

                        

                        onchange="angular.element(this).scope().previewPhoto(event)"

                        >

                        

                          

                          thumbnail" src="" alt="" ng-src="{{ photo }}"/>

                        

                      

                      

                        Hình kèm theo

                        

                        onchange="angular.element(this).scope().previewAttachments(event)" multiple />

                        

                          

                              

                                  {{ attachment }}

                              

                          

                        

                      

                    

 

 

Bài viết liên quan