2016-12-27 74 views
3

我需要通过AngulaJS上传多个文件..怎么样?如何在AngularJS上传多个文件

通过这个代码我只能上传一个文件,但我需要修改这个代码能够上传多文件

我的HTML代码:

<uib-tab index="5" heading="{{'uploadFile' | translate}}" select="tab.tabName = 'uploadFile'"> 
    <div class="form-group"> 
     <div class="row"> 
      <div class="col-md-12"> 
       <span class="dicom_uploader_title">{{'fileToUpload' | translate}}</span> 
       <input type="file" class="dicom_uploader_input" file-model="myFile" accept="*" multiple /> 
       <button ng-click="uploadFileNotDicom();" class="btn btn-default">{{'uploadFile' | translate}}</button> 
      </div> 
     </div> 
    </div> 
    <div> 
     <h4>{{'otherFilesForPatient' | translate}}</h4> 
     <button ng-repeat="otherFile in otherFiles" class="btn btn-flat margin-item" ng-click="getDicomFile(otherFile.id,$index)" >{{otherFile.file_name}}.{{otherFile.extention}}</button> 
    </div> 
</uib-tab> 

我angularJS代码:

$scope.uploadFileNotDicom = function(){ 
    var file = $scope.myFile; 
    UploadFileService.upload_file(file,null,$scope.patientID).then(function(response){ 
     modalObject = GeneralService.makeModal(2000,{ 
      templateUrl:'partials/dashboard/callFallModal.html', 
      controller:'callFallCtrl', 
      resolve:{ 
       modalStatus:function(){ 
        var modalStatus = {}; 
        modalStatus.msg = 'file has been uploaded successfully'; 
        modalStatus.class = 'success'; 
        return modalStatus; 
       } 
      } 
     },null); 
    },function(err){ 
     modalObject = GeneralService.makeModal(2000,{ 
      templateUrl:'partials/dashboard/callFallModal.html', 
      controller:'callFallCtrl', 
      resolve:{ 
       modalStatus:function(){ 
        var modalStatus = {}; 
        modalStatus.msg = err; 
        modalStatus.class = 'error'; 
        return modalStatus; 
       } 
      } 
     },null); 
    }) 
}; 

上传文件服务:

services.factory('UploadFileService',['$http','$q','CONFIG','User',function($http, $q, CONFIG,User){ 

var upload_file = function(file,collectionID,patientID){ 
    var file_uploader = $q.defer(), 
     user = User.getUser(), 
     fd = new FormData(); 
     fd.append('uploadfile', file); 
     fd.append('pat_id', patientID); 
     fd.append('collection_id',collectionID); 
    $http.post(CONFIG.url+'pat-files/create-files', fd, { 
      transformRequest: angular.identity, 
      headers: {'Content-Type': undefined} 
     }) 
     .success(function(data){ 
      file_uploader.resolve(data); 
     }) 
     .error(function(err){ 
      file_uploader.reject(err); 
     }); 

    return file_uploader.promise; 
}; 
var createCollection = function(collectionName, patient_id){ 
    var collection = $q.defer(), 
     user = User.getUser(), 
     collectionData = { 
      "patient_profile_id": patient_id, 
      "collection_name":collectionName 
     }; 
    $http.post(CONFIG.url+'dicom-collection', collectionData, { 
      headers: { 
       'Content-Type': 'application/json', 
       Authorization:'Bearer ' + user.token 
      } 
     }) 
     .success(function(data){ 
      collection.resolve(data); 
     }) 
     .error(function(err){ 
      collection.reject(err); 
     }); 

    return collection.promise; 
}; 

return { 
    upload_file:upload_file, 
    createCollection:createCollection 
} }]); 

而且我Yii2代码:

public function actionCreateFiles() 
{ 

    if(\Yii::$app->request->isPost) 
    { 
     $allowed_extensions = \Yii::$app->params['allowed_extensions']; 
     $upload_file = UploadedFile::getInstanceByName('uploadfile'); 

     $file_ext = $upload_file->getExtension(); // get file extention 
     if (!in_array(strtolower($file_ext), $allowed_extensions)){ 
      \Yii::$app->response->setStatusCode(415); 
      return "File Error, '" . $upload_file->getExtension()."' is not an acceptable extension!"; 
     } 
     $file_basename = $upload_file->getBaseName(); // get file name without extension 
     $relative_upload_path = Yii::getAlias('@uploaded_files_dir'); 
     $upload_path = realpath(Yii::$app->basePath). DIRECTORY_SEPARATOR. $relative_upload_path; 
     if (!file_exists($upload_path)) { 
      mkdir ($upload_path, 0777); 
     } 
     $newfilename = uniqid(date('U').'_'.md5($file_basename),true) . '.'. $file_ext; 
     $file_path = $upload_path . DIRECTORY_SEPARATOR . $newfilename; 

     if($save_result = $upload_file->saveAs($file_path)) { 
      $pat_id = \Yii::$app->request->getBodyParam('pat_id'); 
      $collection_id = \Yii::$app->request->getBodyParam('collection_id'); 
      $user_id = \Yii::$app->user->identity->id; 
      $PatFiles = new PatFiles(); 
      $PatFiles->users_id = $user_id; 
      $PatFiles->file_name = $file_basename; 
      $PatFiles->file_path = $newfilename; 
      $PatFiles->enc_key = "xyz";  ////not true but assumed 
      $PatFiles->extention = $file_ext; 
      $PatFiles->files_type_id = ($file_ext === 'dcm')?1:2; //// DICOM file 
      $PatFiles->patient_profile_id = $pat_id; 
      $PatFiles->collection_id = ($collection_id>0)?$collection_id:null; 
      if($PatFiles->save()) { 
       return "File uploaded successfully."; 
      }else{ 
       return $PatFiles->getErrors(); 
      } 
     } 
     return $save_result; 
    } 

} 

感谢

+0

你可能想用这个[NG2文件上传(http://valor-software.com/ng2-file-upload/)模块 – adriancarriger

+0

没有办法修改这个代码? @adriancarriger – khaledbelal

+0

该链接实际上是Angular 2,看起来像你需要AngularJS,所以也许你想[ng-file-upload](https://github.com/danialfarid/ng-file-upload) – adriancarriger

回答

1

我怀疑你的fileModel指令不更改绑定多个文件。

下面是一个工作示例,指令fileModel在发生更改时更新模型。在服务uploadFileService中,文件被附加到FormData对象。

angular.module('app', []) 
 
    .controller('uploadCTrl', uploadCTrl) 
 
    .directive('fileModel', fileModelDirective) 
 
    .service('uploadFileService', uploadFileService); 
 

 
// Controller 
 
uploadCTrl.$inject = ['uploadFileService']; 
 

 
function uploadCTrl(uploadFileService) { 
 
    var vm = this; 
 
    vm.files = []; 
 
    vm.upload = upload; 
 

 
    function upload() { 
 
    uploadFileService.upload(vm.files); 
 
    } 
 
} 
 

 
// Directive 
 
fileModelDirective.$inject = ['$parse']; 
 

 
function fileModelDirective($parse) { 
 
    return { 
 
    restrict: 'A', 
 
    link: function(scope, el, attrs) { 
 

 
     var 
 
     filesModel = $parse(attrs.fileModel), 
 
     filesSet = filesModel.assign; 
 

 
     el.bind('change', function() { 
 

 
     var files = []; 
 
     angular.forEach(el[0].files, function(item) { 
 

 
      files.push({ 
 
      name: item.name, 
 
      size: item.size, 
 
      url: URL.createObjectURL(item), 
 
      _file: item 
 
      }); 
 

 
      scope.$apply(function() { 
 
      filesSet(scope, files); 
 
      }); 
 

 
     }); 
 

 
     }); 
 

 
    } 
 
    } 
 
} 
 

 
// Service 
 
uploadFileService.$inject = ['$http']; 
 
function uploadFileService($http) { 
 
    var _form 
 
    Data = new FormData(); 
 
    var service = { 
 
    upload: upload 
 
    } 
 

 
    return service; 
 

 
    function upload(files) { 
 
    _formData = new FormData(); 
 

 
    angular.forEach(files, function(file) { 
 
     _formData.append('files', file._file, file.name); 
 
    }); 
 
    
 
    // Post '_formData' 
 
    console.log(_formData.getAll('files')); 
 

 
    } 
 

 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> 
 

 
<body ng-app="app"> 
 

 
    <div ng-controller="uploadCTrl as up"> 
 
    <form> 
 
     <input type="file" file-model="up.files" multiple /> 
 
     <br> 
 
     <br> 
 
     <button ng-click="up.upload()">UPLOAD</button> 
 
    </form> 
 
    </div> 
 

 
</body>