3

I need to upload multi files by AngulaJS .. How?

By this code i can upload a single file only but i need edit this code to able upload multi files

My HTML code:

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

My angularJS code is :

    $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 service :

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

And my Yii2 code is :

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

}

thanks

11
  • You might like using this ng2-file-upload module Commented Dec 27, 2016 at 21:42
  • no way to edit this code? @adriancarriger Commented Dec 28, 2016 at 19:30
  • That link was actually for Angular 2, looks like you need AngularJS so maybe you would like ng-file-upload Commented Dec 28, 2016 at 19:34
  • Sorry i meen i need to edit my code not use new module. Commented Dec 28, 2016 at 20:20
  • I'm not sure what's wrong.. I see that you're using the multiple attribute.. do you get any errors? Commented Dec 28, 2016 at 20:23

1 Answer 1

1

I suspect your fileModel directive is not binding multiple files on change.

Here is a working example, the directive fileModel updates the model when there is a change. In the service uploadFileService the files are appended to the FormData object.

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.