angularjs 和 ng-file-upload - 使用多个 ngf-select 输入的多个文件上传

angularjs and ng-file-upload - multiple file upload with multiple ngf-select inputs

背景:

我有一个表单,可以将两个文件连同以另一种表单创建的 Javascript 对象文字上传到服务器。

上传这些文件是可选的,因此可能有 none,一个或两个,但始终需要 Javascript 对象文字。

表格正在工作,文件正在上传为 none,一个或两个连同 Javascript 对象字面量。

问题:

我遇到的问题是捕获响应并根据响应采取行动。进度事件似乎被正确捕获,但看起来响应对象不是,这可能是我使用 ng-file-upload 的方式的副作用,或者可能只是服务器端没有返回正确的响应对象。

有人可以确认一下用法没问题吗?

我尝试将 .error().success() 添加到 Upload.upload 调用但它说 Upload.upload(...).then(...).error is not a function or Upload.upload(...).then(...).success 不是函数

源代码:

这只是 POC,不是生产代码。

控制器

(function () {
  'use strict';

  angular
    .module('transcend.kyc.signup')
    .controller('SignupFileUpload', SignupFileUpload);

    SignupFileUpload.$inject = ['$scope','Upload', '$log', '$timeout','$location','URLS','SignupService','usSpinnerService','$anchorScroll'];

    function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll) {
      $log.debug('ENTERING SIGNUP UPLOAD CONTROLLER %s', JSON.stringify(this));

      var params = $location.search();
      var customerInfo = SignupService.getCustomerInfo();
      var uploadData = {};

      $log.debug('CUSTOMER INFO'+JSON.stringify(customerInfo));

      if (typeof Object.keys(customerInfo)[0] === 'undefined') {
        $log.debug('SIGNUP - Must provide customerInfo');
        $location.path('/signup');
      }

      $scope.mobileUpload = function(form) {
        usSpinnerService.spin('spinner');
        $log.debug('Starting Mobile Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);
        $log.debug('No Files are uploaded for mobile client');
        $log.debug('Adding customerInfoPart to uploadData');
        uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);
        $log.debug('Upload data - ' + JSON.stringify(uploadData));
        $log.debug('Uploading data');

        Upload.upload({
          url: URLS.BASE + URLS.FILE_UPLOAD,
          data: uploadData
        }).then(function (response) {
          // file is uploaded successfully
          usSpinnerService.stop('spinner');
          $log.debug('Mobile Upload Status - ' + response.status);
          $timeout(function () {
              $scope.serverMessage = response.data;
          });
          if (response.status===204) {
            $location.path('/signup-confirmation');
            SignupService.setCustomerSignupStatus(true);
          } 
        }, function (response) {
          // handle error
          $log.debug('Signup failed with status ' + response.status);
          handleError(response);
        }, function (evt) {
          $scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
          $log.debug('Mobile Upload progress ' + $scope.progress);
        });
      };

      $scope.uploadFiles = function(idFile,addressFile,form) {
        usSpinnerService.spin('spinner');

        $log.debug('Starting Upload Process to resource - ' + URLS.BASE + URLS.FILE_UPLOAD);

        $log.debug('Checking for files to upload');
        if (idFile) {
          $log.debug('idFile found, adding to uploadData');
          uploadData.idDocument = idFile;
        }
        if (addressFile) {
          $log.debug('addressFile found, adding to uploadData');
          uploadData.addressDocument = addressFile;
        }

        $log.debug('Adding customerInfoPart to uploadData');
        uploadData.customerInfoPart = Upload.jsonBlob(customerInfo);

        $log.debug('Upload data - ' + JSON.stringify(uploadData));

        $log.debug('Uploading data');

        Upload.upload({
          url: URLS.BASE + URLS.FILE_UPLOAD,
          data: uploadData
        }).then(function (response) {
          // file is uploaded successfully
          usSpinnerService.stop('spinner');
          $log.debug('Upload Status - ' + response.status);

          $timeout(function () {
              $scope.serverMessage = response.data;
          });

          if (response.status===204) {
            $location.path('/signup-confirmation');
            SignupService.setCustomerSignupStatus(true);
          } 
        }, function (response) {
          // handle error
          $log.debug('Signup failed with status ' + response.status);
          handleError(response);

        }, function (evt) {
          // progress notify
          $scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
          $log.debug('Upload progress ' + $scope.progress);
        });
      };

      function handleError(error) {
          usSpinnerService.stop('spinner');
          scrollToServerMessage();
          $scope.serverMessage = 'Signup failed with status ' + error.status;
      }

      function scrollToServerMessage() {
          var old = $location.hash();
          $location.hash('serverMessage');
          $anchorScroll();
          //reset to old to keep any additional routing logic from kicking in
          $location.hash(old);
      }
    }
}());

HTML

        <form name="signupForm">
      <div class="panel panel-default no-bottom-margin">
        <div class="hidden-md hidden-lg">
          <div class="panel-heading no-border">
              <h2 class="panel-title" translate>ID Documents</h2>
              <hr/>
          </div>
          <div class="panel-body">
              <span><p>Document upload facility is not supported on mobile devices. Please send your ID documents to <a href="mailto:someone@somewhere.com" target="_top"><span>someone@somwehere.com</span></a> after you complete sign up.</p>
              <p>You will need to scan and upload the following two documents:<br/> 
              - Proof of identity (passport or ID card)<br/>
              - Proof of address (utility bill, bank statement or government issued letter within the last 3 months)</p></span>
          </div>
          <div class="panel-footer">
            <div class="align-right">
                <button type="button"
                        id="proceedBtn"
                        ng-click="mobileUpload(signupForm)" class="btn btn-sm xs-display-block"
                        translate>Complete Sign up
                </button>
            </div>
          </div>
        </div>
        <div class="hidden-xs hidden-sm">
          <div class="form-control-wrapper">
            <div class="panel-heading no-border">
                <h2 class="panel-title" translate>ID Documents</h2>
                <hr/>
                <p>Please upload a copy of your passport, drivers license, or any other government issued identification</p>
            </div>
            <div class="panel-body">
              <div ng-class="{'has-error': signupForm.idfile.$invalid && signupForm.idfile.$dirty,
                            'has-success': signupForm.idfile.$valid}">
                <div  class="btn btn-sm btn-primary"
                      ngf-select=""
                      ngf-max-size="2MB" 
                      ng-model="idFile" 
                      accept="image/*,application/pdf"  
                      ngf-pattern="'image/*,application/pdf'"
                      required="false"
                      id="idfile"
                      name="idfile"><span ng-if="signupForm.idfile.$valid">Change file</span><span ng-if="!signupForm.idfile.$valid">Add file</span>
                </div>  
                <div class="form-group has-error has-feedback" ng-show="signupForm.idfile.$error.maxSize">
                  <span class="input-status placement-left">File is too large, maximum size is 2MB</span>
                </div>
                <div ng-show="signupForm.idfile.$valid" class="form-control-wrapper">
                  <img ngf-thumbnail="idFile" class="thumb"/>
                  <div class="align-right">
                    <button ng-click="idFile = null" ng-show="idFile" class="btn btn-sm btn-warning">Remove</button>
                  </div>
                </div>          
              </div>
            </div>
            <div class="panel-heading no-border">
                <h2 class="panel-title" translate>Proof of address</h2>
                <hr/>
                <p>Please upload a copy of a utility bill or your driving licence</p>
            </div>
            <div class="panel-body">    
              <div ng-class="{'has-error': signupForm.addressfile.$invalid && signupForm.addressfile.$dirty,
                            'has-success': signupForm.addressfile.$valid}">
                <div  class="btn btn-sm btn-primary"
                      ngf-select=""
                      ngf-max-size="2MB" 
                      ng-model="addressFile" 
                      accept="image/*,application/pdf"  
                      ngf-pattern="'image/*,application/pdf'"
                      required="false"
                      id="addressfile"
                      name="addressfile"><span ng-if="signupForm.addressfile.$valid">Change file</span><span ng-if="!signupForm.addressfile.$valid">Add file</span>
                </div>
                <div class="form-group has-error has-feedback" ng-show="signupForm.addressfile.$error.maxSize">
                  <span class="input-status placement-left">File is too large, max size is 2 MB</span>
                </div>
                <div ng-show="signupForm.addressfile.$valid" class="form-control-wrapper">
                  <img ngf-thumbnail="addressFile" class="thumb"/>
                  <div class="align-right">
                    <button ng-click="addressFile = null" ng-show="addressFile" class="btn btn-sm btn-warning">Remove</button>
                  </div>
                </div>
              </div>
            </div>
            <div class="panel-footer">
              <div class="align-right">
                  <button type="button"
                          id="proceedBtn"
                          ng-click="uploadFiles(idFile,addressFile,signupForm)" 
                          class="btn btn-primary"
                          translate>Complete Sign up
                  </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>

控制台:

1 - 没有附加文件 只有 Javascript 对象文字:

2015-11-16 14:29:43.760 angular.js:11706 Starting Upload Process to resource - http://poc.services.co.uk/v1/customers/signup
2015-11-16 14:29:43.760 angular.js:11706 Checking for files to upload
2015-11-16 14:29:43.761 angular.js:11706 Adding customerInfoPart to uploadData
2015-11-16 14:29:43.762 angular.js:11706 Upload data - {"customerInfoPart":{"_ngfBlob":true}}
2015-11-16 14:29:43.762 angular.js:11706 Uploading data
2015-11-16 14:29:43.763 angular.js:11706 SESSSION INJECTOR Credentials 409f3c71-3936-48f9-ad71-fee11d9077c9
2015-11-16 14:29:44.025 angular.js:11706 Upload progress 100
2015-11-16 14:29:44.025 angular.js:11706 Upload progress 100
2015-11-16 14:29:45.611 angular.js:11706 Upload Status - 204  

2 - 两个附加了 Javascript 对象文字的文件

2015-11-16 14:36:51.845 angular.js:11706 Starting Upload Process to resource - http://poc.services.co.uk/v1/customers/signup
2015-11-16 14:36:51.845 angular.js:11706 Checking for files to upload
2015-11-16 14:36:51.845 angular.js:11706 idFile found, adding to uploadData
2015-11-16 14:36:51.845 angular.js:11706 addressFile found, adding to uploadData
2015-11-16 14:36:51.845 angular.js:11706 Adding customerInfoPart to uploadData
2015-11-16 14:36:51.848 angular.js:11706 Upload data - {"idDocument":{"$ngfDataUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACegAAAGUCAYAAABEc1DzAAAMFmlDQ…EJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgATWMYH/B2nQc4eYA6LeAAAAAElFTkSuQmCC"},"addressDocument":{"$ngfDataUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACc4AAAKYCAYAAABAGvmCAAAMFmlDQ…ABBBBAAAEEEEAAAQQQQAABBBBAAAEEEEAAAQQQQAABJ/B/U81Hrz5c8Q0AAAAASUVORK5CYII="},"customerInfoPart":{"_ngfBlob":true}}
2015-11-16 14:36:51.858 angular.js:11706 Uploading data
2015-11-16 14:36:51.864 angular.js:11706 SESSSION INJECTOR Credentials 409f3c71-3936-48f9-ad71-fee11d9077c9
2015-11-16 14:36:52.142 angular.js:11706 Upload progress 38
2015-11-16 14:36:52.342 angular.js:11706 Upload progress 42
2015-11-16 14:36:52.441 angular.js:11706 Upload progress 46
2015-11-16 14:36:52.542 angular.js:11706 Upload progress 50
2015-11-16 14:36:52.642 angular.js:11706 Upload progress 59
2015-11-16 14:36:52.741 angular.js:11706 Upload progress 63
2015-11-16 14:36:52.843 angular.js:11706 Upload progress 71
2015-11-16 14:36:52.942 angular.js:11706 Upload progress 76
2015-11-16 14:36:53.043 angular.js:11706 Upload progress 84
2015-11-16 14:36:53.143 angular.js:11706 Upload progress 88
2015-11-16 14:36:53.243 angular.js:11706 Upload progress 97
2015-11-16 14:36:53.344 angular.js:11706 Upload progress 100
2015-11-16 14:36:53.344 angular.js:11706 Upload progress 100 Upload data - 

3 - 一个文件附加了 Javascript 对象文字

2015-11-16 14:40:54.263 angular.js:11706 Starting Upload Process to resource - http://poc.services.co.uk/v1/customers/signup
2015-11-16 14:40:54.263 angular.js:11706 Checking for files to upload
2015-11-16 14:40:54.263 angular.js:11706 idFile found, adding to uploadData
2015-11-16 14:40:54.264 angular.js:11706 Adding customerInfoPart to uploadData
2015-11-16 14:40:54.265 angular.js:11706 Upload data - {"idDocument":{"$ngfDataUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACegAAAGUCAYAAABEc1DzAAAMFmlDQ…EJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgATWMYH/B2nQc4eYA6LeAAAAAElFTkSuQmCC"},"customerInfoPart":{"_ngfBlob":true}}
2015-11-16 14:40:54.271 angular.js:11706 Uploading data
2015-11-16 14:40:54.272 angular.js:11706 SESSSION INJECTOR Credentials 409f3c71-3936-48f9-ad71-fee11d9077c9
2015-11-16 14:40:54.536 angular.js:11706 Upload progress 64
2015-11-16 14:40:54.736 angular.js:11706 Upload progress 71
2015-11-16 14:40:54.836 angular.js:11706 Upload progress 78
2015-11-16 14:40:54.937 angular.js:11706 Upload progress 92
2015-11-16 14:40:55.037 angular.js:11706 Upload progress 99
2015-11-16 14:40:55.138 angular.js:11706 Upload progress 100
2015-11-16 14:40:55.138 angular.js:11706 Upload progress 100

4 - 带有 Javascript 文字对象并尝试 .error()

的单个文件
2015-11-16 15:55:59.111 angular.js:11706 Starting Upload Process to resource - http://epconnect.devtest.aspone.co.uk/v1/customers/signup
2015-11-16 15:55:59.111 angular.js:11706 Checking for files to upload
2015-11-16 15:55:59.111 angular.js:11706 idFile found, adding to uploadData
2015-11-16 15:55:59.111 angular.js:11706 Adding customerInfoPart to uploadData
2015-11-16 15:55:59.113 angular.js:11706 Upload data - {"idDocument":{"$ngfDataUrl":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACegAAAGUCAYAAABEc1DzAAAMFmlDQ…EJSEACEpCABCQgAQlIQAISkIAEJCABCUhAAhKQgATWMYH/B2nQc4eYA6LeAAAAAElFTkSuQmCC"},"customerInfoPart":{"_ngfBlob":true}}
2015-11-16 15:55:59.118 angular.js:11706 Uploading data
2015-11-16 15:55:59.126 angular.js:11706 TypeError: Upload.upload(...).then(...).error is not a function
at Scope.SignupFileUpload.$scope.uploadFiles (signup-file-upload.controller.js:93)
at $parseFunctionCall (angular.js:12474)
at angular-touch.js:481
at Scope.$eval (angular.js:14570)
at Scope.$apply (angular.js:14669)
at HTMLButtonElement.<anonymous> (angular-touch.js:480)
at HTMLButtonElement.jQuery.event.dispatch (jquery.js:4435)
at HTMLButtonElement.elemData.handle (jquery.js:4121)(anonymous function) @ angular.js:11706(anonymous function) @ angular.js:8619Scope.$apply @ angular.js:14671(anonymous function) @ angular-touch.js:480jQuery.event.dispatch @ jquery.js:4435elemData.handle @ jquery.js:4121
2015-11-16 15:55:59.127 angular.js:11706 SESSSION INJECTOR Credentials 4904d093-11fd-4f5c-8d12-af9d837896bb
2015-11-16 15:55:59.393 angular.js:11706 Upload progress 64
2015-11-16 15:55:59.594 angular.js:11706 Upload progress 71
2015-11-16 15:55:59.695 angular.js:11706 Upload progress 78
2015-11-16 15:55:59.796 angular.js:11706 Upload progress 92
2015-11-16 15:55:59.896 angular.js:11706 Upload progress 99
2015-11-16 15:55:59.997 angular.js:11706 Upload progress 100
2015-11-16 15:55:59.998 angular.js:11706 Upload progress 100

正如 danial 所提到的,在某些情况下服务器端没有正确的响应。我仍然无法使用 .error 或 .success 但我至少能够在我现有的控制器逻辑中处理成功和错误情况。

欢迎对控制器提出任何改进或建议。