提交表单后,而不是选择它后,如何上传文件

时间:2018-10-26 20:08:32

标签: angularjs

现在,从打开的窗口中选择文件后,我会将文件上传到文件夹中。我只需要选择此文件,然后在表单提交时最终上传。我还需要保存要上传的文件的名称,以便可以将其保存到数据库。这是我的一些代码:

HTML

<form id="requisitionForm" 
  name="$parent.requisitionForm" 
  method="post" 
  class="form-horizontal" 
  enctype="multipart/form-data">
  <input type="file" 
    id="quoteAttachment" 
    name="quoteAttachment" 
    ngf-select="upload($file)" 
    class="form-control fixInput" 
    data-ng-model="vm.requisition.pOR_Detail.quote_Attachment" 
    data-ng-disabled="vm.disableEditing" />
  <button type="button" 
    data-ng-show="!vm.itemToEdit.iD && !vm.disableEditing2 && (vm.newRequisition || vm.requisition.status_ID === 1)" 
    class="btn btn-primary dissolve-animation" 
    data-ng-click="vm.saveAndSubmit()">Save & Submit</button>
</form>

JavaScript

$scope.upload = function (file) {
  Upload.upload({
    url: '../../UploadHandler2.ashx',
    data: { file: file, 'username': 'TEST' }
  }).then(function (resp) {
    console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' + resp.data);
  }, function (resp) {
    console.log('Error status: ' + resp.status);
  }, function (evt) {
    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
  });
};

function saveAndSubmit() {
  if ($scope.requisitionForm.$valid) {
    isSave = true;
    datacontext
    .save(vm.requisition, vm.newRequisition)
    .then(function (data) {
      vm.newRequisition = false;
      grabEmailsAndSend(vm.requisition, 'submitted');
    });
    $window.history.back();
  }
  else {
    logError('Error: <br> Invalid Form please fill out the required fields');
  }
}

1 个答案:

答案 0 :(得分:0)

您不必立即上传文件。使用其他函数和变量选择文件后,只需捕获该文件即可。

HTML

<input type="file" 
  ngf-select="fileSelected($file)" 
/>

JavaScript

var selectedFile;
$scope.fileSelected = function(file) {
  selectedFile = file;
};

function uploadFile(file) {
  Upload.upload({
    url: '../../UploadHandler2.ashx',
    data: { file: file, 'username': 'TEST' }
  }).then(function (resp) {
    console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' + resp.data);
  }, function (resp) {
    console.log('Error status: ' + resp.status);
  }, function (evt) {
    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
  });
}

function saveAndSubmit() {
  uploadFile(selectedFile);  // <------------you can call here
  if ($scope.requisitionForm.$valid) {
    isSave = true;
    datacontext
    .save(vm.requisition, vm.newRequisition)
    .then(function (data) {
      // <----------------------- or here, or anywhere, really
      vm.newRequisition = false;
      grabEmailsAndSend(vm.requisition, 'submitted');
    });
    $window.history.back();
  }
  else {
    logError('Error: <br> Invalid Form please fill out the required fields');
  }
}