使用ng-file-upload和angularjs进行内容处理

时间:2015-11-17 09:35:23

标签: javascript angularjs fileapi ng-file-upload

背景

我正在使用ng-file-upload以单独的ngf-selection和Javascript对象文字提交两个文件。我遇到的问题是,当发送请求时,所有部分的内容处理都设置为表单数据,但我期望的是两个文件的内容处理是附件。

问题:

我是否有办法覆盖表单部分的内容处理方式,使其对于文件 附件 而不是 form-data < /强>

CODE

控制器:

(function () {
  'use strict';

  angular
    .module('poc.fileUpload')
    .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@somewhere.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="popover-wrapper">
                <a href="" 
                   ng-show="!signupForm.idfile.$valid"
                   class="top-left" 
                   role="button"
                   data-toggle="popover"
                   data-placement="top"
                   data-content-source="#popover-content"
                   data-trigger="click"
                   transcend-popover
                   content="{{'In order to set up your account, we need you to provide us with a copy of a valid national ID card or passport and a proof of address. These documents are kept safely for our records, and allow us to verify your identity. There is a limit of 2MB per file.' |translate}}">
                    <small><span class="icon-popover"></span>&nbsp;<span translate> Why is this needed?</span>
                    </small>
                </a>
            </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="popover-wrapper">
                <a href=""
                   ng-show="!signupForm.addressfile.$valid" 
                   class="top-left" 
                   role="button"
                   data-toggle="popover"
                   data-placement="top"
                   data-content-source="#popover-content"
                   data-trigger="click"
                   transcend-popover
                   content="{{'In order to set up your account, we need you to provide us with a copy of a valid national ID card or passport and a proof of address. These documents are kept safely for our records, and allow us to verify your identity. There is a limit of 2MB per file.' |translate}}">
                    <small><span class="icon-popover"></span>&nbsp;<span translate>Why is this needed?</span>
                    </small>
                </a>
            </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>

当前要求: File upload post

1 个答案:

答案 0 :(得分:0)

因此,虽然没有一个图书馆允许我这样做,但仍然需要更改内容处理和其他内容,所以我设法在以下问题的帮助下完成了https://stackoverflow.com/a/28143262/844809

我仍然在UI中使用ng-file-upload获取各种有用的功能,但在控制器中我构建了自己的帖子。

(function () {
  'use strict';

  angular
    .module('poc.fileUploads')
    .controller('SignupFileUpload', SignupFileUpload);

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

    function SignupFileUpload($scope, Upload, $log, $timeout, $location, URLS, SignupService,usSpinnerService,$anchorScroll,$http) {
      $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.uploadFiles = function(idFile,addressFile,form) {
        usSpinnerService.spin('spinner');

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

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

        $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('Upload data - ' + JSON.stringify(uploadData));

        $log.debug('Uploading data');

        var epochTicks = 621355968000000000;
        var ticksPerMillisecond = 10000;
        var yourTicks = epochTicks + ((new Date()).getTime() * ticksPerMillisecond);

        var boundary='---------------------------'+yourTicks;
        var header='--'+boundary+'\r\n';
        var footer='\r\n--'+boundary+'--\r\n';
        var contenttype='multipart/form-data; boundary='+boundary;

        var jsonContents=header+'Content-Disposition: form-data; name="customerInfoPart"\r\n';
        jsonContents+='Content-Type: application/json\r\n';
        jsonContents+='Content-Length: '+JSON.stringify(customerInfo).length+'\r\n\r\n';
        jsonContents+=JSON.stringify(customerInfo)+'\r\n';

        var idFileContents=header+'Content-Disposition: form-data; name="idDocument"; filename="'+$scope.idFile.name+'"\r\n';
        idFileContents+='Content-Transfer-Encoding: binary\r\n';
        idFileContents+='Content-Type: '+ $scope.idFile.type+'\r\n';
        idFileContents+='Content-Length: '+ $scope.idFile.size +'\r\n\r\n';

        var idFileReader = new FileReader();
//        idFileReader.readAsArrayBuffer($scope.idFile);

        var addressFileContents=header+'Content-Disposition: form-data; name="addressDocument"; filename="'+$scope.addressFile.name+'"\r\n';
        addressFileContents+='Content-Transfer-Encoding: binary\r\n';
        addressFileContents+='Content-Type: '+$scope.addressFile.type+'\r\n';
        addressFileContents+='Content-Length: '+$scope.addressFile.size+'\r\n\r\n';

        var addressFileReader = new FileReader();
//        addressFileReader.readAsArrayBuffer($scope.addressFile);

        var blob=new Blob([jsonContents,idFileReader.readAsArrayBuffer($scope.idFile),idFileReader,addressFileReader.readAsArrayBuffer($scope.addressFile),addressFileReader,footer]);

        $log.debug(blob.toString());

        $http.post(
          URLS.BASE + URLS.FILE_UPLOAD,
          blob,
          {'headers':{'Content-Type':contenttype}}
        ).success(function (data, status, headers, config) {
          // file is uploaded successfully
          usSpinnerService.stop('spinner');
          $log.debug('Upload Status - ' + status);

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

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

      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);
      }
    }
}());