Content-Disposition с ng-file-upload и angularjs

Предыстория:

Я использую ng-file-upload для отправки двух файлов в отдельные ngf-выборы, а также литерал объекта Javascript. Проблема, с которой я сталкиваюсь, заключается в том, что при отправке запроса расположение содержимого всех частей устанавливается в данные формы, но я ожидаю, что расположение содержимого двух файлов будет вложением.

Вопрос:

Есть ли способ переопределить расположение содержимого частей формы, чтобы оно было вложением для файлов, а не данными формы? ?

КОД

Контроллер:

(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:[email protected]" target="_top"><span>[email protected]</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>

Текущий запрос: Сообщение о загрузке файла


person Graham    schedule 17.11.2015    source источник
comment
Глядя на FileAPI.js в ng-file-upload, я вижу в строке 2621, что есть функция toMultiPartData: строка 2626... '--_' + border + ('\r\nContent-Disposition: form-data; name='+ file.name +''+ (file.file ? '; filename='+ encodeURIComponent(file.file) +'' : '') + (file.file ? '\r\nContent-Type: ' + (file.type || 'application/octet-stream'): '') .... Я думаю, что, возможно, именно здесь устанавливаются данные формы для всех элементов формы.   -  person Graham    schedule 17.11.2015
comment
Я поговорил с автором FileAPI, используемого в ng-file-upload и в соответствии с ietf.org/ rfc/rfc1867.txt спецификации form-data — это ожидаемое расположение контента. Меня заинтересовало это изменение из-за поведения на стороне сервера в apache-camel и apache-cxf. Я думаю, что мне придется искать решения вместо этого   -  person Graham    schedule 17.11.2015
comment
я дополнительно просмотрел спецификации ietf.org/rfc/rfc1867.txt, и похоже, что content-disposition=attachment является действительной настройкой, в конце концов   -  person Graham    schedule 17.11.2015
comment
Мне не удалось найти каких-либо быстрых способов обойти это, тем временем я смотрю на применение transformRequest к данным в вызове Upload.upload и таким образом меняю расположение содержимого.   -  person Graham    schedule 17.11.2015
comment
Это не имеет ничего общего с FileAPI, если только вы не тестируете его в IE8-9. Файлы отправляются как запрос multipart/form-data, поэтому расположение содержимого каждой части — это form-data. Если вы хотите отправить двоичный файл файла напрямую, вы можете использовать Upload.http()   -  person danial    schedule 18.11.2015


Ответы (1)


Поэтому, хотя ни одна из библиотек не позволит мне это сделать, мне все равно нужно было изменить расположение контента и другие вещи, поэтому мне удалось сделать это с помощью следующего вопроса https://stackoverflow.com/а/28143262/844809

Я все еще использую 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);
      }
    }
}());
person Graham    schedule 18.11.2015