自定义上传+提交一个按钮angularjs

时间:2016-04-21 04:09:02

标签: javascript angularjs file-upload

我试图在角度上找到类似的东西,但并不幸运。我发现我必须以某种方式使用#34; onchange"。我的代码看起来不像:

   <form ng-controller="uploadCtrl as up" name="up.upload_form">
       <div class="fileUpload btn btn-primary">
                    <span>Upload</span>
                    <input type="file" class="upload"
                           ngf-select
                           ng-model="up.file"
                           name="file"
                           ngf-max-size="20MB"/></div>
     <button type="submit" class="btn btn-default" ng-click="up.submit()">Upload</button>
   <i ng-show="up.upload_form.file.$error.required">*required</i><br>
   <i ng-show="up.upload_form.file.$error.maxSize">File too large
      {{up.file.size / 1000000|number:1}}MB: max 20M</i>
   <button class="btn btn-default"  ng-click="compare_it()">Compare it</button>
                    <pre>{{up.progress}}</pre>
 </form>

这是我的控制器

app.controller('uploadCtrl',['Upload','$window',function(Upload,$window){
    var vm = this;
    vm.submit = function(){ //function to call on form submit
        if (vm.upload_form.file.$valid && vm.file) {//check if from is valid

            //console.log(vm.file.name);
            vm.upload(vm.file); //call upload function
            //vm.file.name = prompt("put you name");
        }
    };

    vm.upload = function (file) {
        Upload.upload({
            url: '/upload', //webAPI exposed to upload the file
            data:{file:file} //pass file as data, should be user ng-model
        }).then(function (resp) { //upload function returns a promise
            if(resp.data.error_code === 0){ //validate success
                $window.alert('Success ' + resp.config.data.file.name + ' uploaded.');
            } else {
                $window.alert('an error occured');
            }
        }, function (resp) { //catch error
            console.log('Error status: ' + resp.status);
            $window.alert('Error status: ' + resp.status);
        }, function (evt) {
            console.log(evt);
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
            vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
        });
    };
}]);

无论如何合并输入类型=&#34;文件&#34;和按钮类型=&#34;提交&#34;?我感谢任何帮助

1 个答案:

答案 0 :(得分:2)

在控制器中:

$scope.$watch("up.file", function() { if (up.file) up.submit() });

或者在视图中:

<input type="file" class="upload"
                       ngf-select
                       ng-model="up.file"
                       ng-change="up.submit()"
                       name="file"
                       ngf-max-size="20MB"/>