如何在AngularJS中上传多个文件

时间:2016-12-27 19:01:13

标签: javascript angularjs yii2

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

通过此代码,我只能上传一个文件,但我需要编辑此代码才能上传多个文件

我的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);
    })
};

UploadFileService服务:

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

}

感谢

1 个答案:

答案 0 :(得分:1)

我怀疑你的numUpdates指令在更改时没有绑定多个文件。

这是一个工作示例,指令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'));

  }

}