Upload angular multi-part

2019-08-10 02:12发布

I made this example: http://jsfiddle.net/ejx68/6/ to upload multi-part file but there are two things i can't do.

1) Upload more than one file. So use the multiple condition on input

2) append other formData() that i have in the controller to the service.

Here the example:

var myApp = angular.module('myApp', []);

myApp.directive('fileModel', ['$parse', 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]);
                });
            });
        }
    };
}]);

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl, callback){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(callback)
        .error(callback);
    }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

    $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' + JSON.stringify(file));
        console.log(fileUpload.fd);

        fileUpload.fd.append('newID', "2");

        var uploadUrl = "http://httpbin.org/post";
        fileUpload.uploadFileToUrl(file, uploadUrl,function(data, status, headers, config){
            if(status == 200)console.log('Success!');
            else console.log('Error!');
        });
    };

}]);


<div ng-controller = "myCtrl">
    <input type="file" file-model="myFile"/>
    <button ng-click="uploadFile()">upload me</button>
</div>

thanks

0条回答
登录 后发表回答