2016年4月25日 星期一

multipart/form-data File Upload with AngularJS


https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs



angular.module('yoApp')

//uploadService
  .service('fileUpload',function ($q,$http) {

    this.uploadFileToUrl = function(file, uploadUrl){

        var deferred = $q.defer();

        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(result){
        console.log(result);
            deferred.resolve(result);
        })
        .error(function(error){
        console.log(error);
            deferred.reject(error);
        });

        return deferred.promise;
    }
  })
  .directive('fileModel',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]);
                });
            });
        }
    };
  })
  .controller('uploadCtrl', function ($scope,fileUpload,$q,$timeout,buildingIndelFactory) {

    $scope.myFile;

    $scope.uploadFile = function(type,label){

        var file = $scope.myFile;
        var uploadUrl = "/upload";

   $q.all([
           fileUpload.uploadFileToUrl(file, uploadUrl)
       ]).then(function(value) {

   }, function(reason) {

   });
     
    };
 

  });

沒有留言:

張貼留言