2015-05-04 65 views
-2

我有一個表單,其中一些表單域是文件上傳。這是我有:使用RESTful API異步上傳文件使用Angular,ng-file-upload使用RESTful API

  1. 用戶填寫表單了
  2. 用戶選擇文件時提交
  3. 用戶按下提交

現在,這就是我想做的事:

  1. 將表單發送到服務器,取回ID
  2. 將文件發送到服務器myreso urce/ID/fileone
  3. 後文件中的兩個服務器myresource/ID/FileTwo傳送 ...

¿我如何執行此文件上傳編程? (我用角的承諾,因此與連續的請求沒有問題... ...)

這裏是我的代碼:

$scope.upload = function (files, url) { 
     if (files && files.length) { 
     for (var i = 0; i < files.length; i++) { 
      var file = files[i]; 
      Upload.upload({ 
      url: url, 
      //fields: {'username': $scope.username}, 
      file: file 
      }).progress(function (evt) { 
      var progressPercentage = parseInt(100.0 * evt.loaded/evt.total); 
      console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name); 
      }).success(function (data, status, headers, config) { 
      console.log('file ' + config.file.name + 'uploaded. Response: ' + data); 
      }); 
     } 
     } 
    }; 

我的HTML:

<input type="file" class="btn btn-danger" ng-file-select ng-model="files" ng-multiple="multiple"> Doit! 

<input class="btn btn-danger" ng-file-select ng-model="files" ng-multiple="multiple">Doit too! 

回答

1

好了,我終於得到了這個。

我這樣做:

  1. 在NG-模型
  2. 驗證一些東西,選擇文件和存儲文件
  3. 提交主模型(一個擁有我要上傳的文件)
  4. 上傳文件到端點/ api/myentity/{id}/resumee,/ api/myentity/{id}/dni和/ api/myentity/{id} /圖片。其中,{id}​​是我在上一步中創建的實體的ID。

所以這裏的訣竅是執行兩個請求,一個創建實體並檢索id,第二個只上傳文件。

的代碼看起來是這樣的:

// This is called every time the user selects a file 
$scope.selectedFile = function (files, doc) { 
     if (doc === 'resumee') $scope.documents.resumee = files.pop(); 
     else if (doc === 'dni') $scope.documents.dni = files.pop(); 
     else if (doc === 'picture') $scope.documents.picture = files.pop(); 
}; 

// This is called when the user submits the form 
$scope.upload = function (docname, url) { 

     var file = $scope.stepThree.documents[docname]; 

     return Upload.upload({ 
     url: url, 
     method: 'POST', 
     headers: {'Content-Type': file.type}, 
     fileFormDataName: docname, 
     data: file, 
     file: file 
     }).progress(function (evt) { 
     var progressPercentage = parseInt(100.0 * evt.loaded/evt.total); 
     console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name); 
     }); 
    }; 

最後,該標記是這樣的:

<div class="form-horizontal"> 
     <div class="form-group"> 
      <div class="col-sm-2"> 
      <label> Resumen Curricular </label> 
      </div> 
      <div class="col-sm-2"> 
      <button class="btn btn-danger" ngf-select ngf-change="selectFile($files, 'resumee')"> Seleccione</button> 
      <p>{{stepThree.documents.resumee.name}}</p> 
      </div> 
     </div> 
</div> 

既然沒有人對這種方法/技術評論,我將以此爲最佳使用文件上傳,角度和REST API來處理世界。