Saturday, 10 June 2017

uploading multiple files using node, multer ,express

i am trying to upload multiple files using multer. I am having three input boxes and one upload button to upload three files at a time.As per the client requirement user needs to select one file at a time and after selecting three files,user can upload all the files in one go.

enter image description here

HTML

<div ng-show="role == '1'"  class="col-sm-4 col-md-4 form-group">
    <label for="basic-url">Upload Your Image (Passport Size)</label>
        <input type="file" class="form-control"  file-model="file.upload" name="myFile" onchange="angular.element(this).scope().photoChanged(this.files)"></label>
            <input type="submit" class="btn btn-primary"  ng-click="Submit('customerimage')" value="Upload" >
            </div>
            <div ng-show="role == '1'"  class="col-sm-4 col-md-4 form-group">

<label for="basic-url">Upload Pan Card image</label>
<input type="file" class="form-control"  file-model="file.upload" name="myFile" onchange="angular.element(this).scope().photoChanged(this.files)"></label>
            <input type="submit" class="btn btn-primary"  ng-click="Submit('pancardimage')" value="Upload" >
            </div>

            <div ng-show="role == '1'"  class="col-sm-4 col-md-4 form-group">

<label for="basic-url">Upload Bank Passbook image</label>
<input type="file" class="form-control"   file-model="file.upload" name="myFile" onchange="angular.element(this).scope().photoChanged(thi`enter code here`s.files)"></label>
            <input type="submit" class="btn btn-primary"  ng-click="Submit('bankimage')" value="Upload" >
            </div>
    </div>

Server.js

var multer=require('multer');
var storage = multer.diskStorage({
          destination: function (req, file, cb) {
            cb(null, 'public/uploads/images/');
          },
          filename: function (req, file, cb) {
              if(! file.originalname.match(/\.(jpeg|jpg|png|JPEG|JPG|PNG)$/)){

                  var err=new Error();
                  err.code="filetype";
                  return cb(err);
              }else{
                  cb(null,Date.now() + '_' + file.originalname);
              }

            //cb(null, file.fieldname + '-' + Date.now());
          }
    });
var upload = multer({ storage: storage }).single('myFile');
app.post('/upload', function (req, res) {
      upload(req, res, function (err) {
              console.log(req.file);

         if (err) {
            if(err.code=='LIMIT_FILE_SIZE'){
                res.json({success:false,message:'file is tool arge'});
            }else if(err.code=='filetype'){
                res.json({success:false,message:'file type is invalid'});
            }else{

                res.json({success:false,message:'file is not selected'});
            }
        }
      else{
          if(!req.file){
              res.json({success:false,message:'no file selected'});
          }
          else{
          console.log(req.file);
               res.json({success:true,message: req.file});
          }
        }

        // Everything went fine
      });
    });

Controller
$scope.file={};
    $scope.Submit=function(name){
        $scope.name = name;
        uploadFile.upload($scope.file).then(function(data){
            if(data.data.success){
                $scope.alert='alert alert-success';
                $scope.message=data.data.message;
                $scope.file={};
                $scope.newCustomer[$scope.name] = 'uploads/images/' + data.data.message.filename;
            }else{
                $scope.alert='alert alert-danger';
                $scope.message=data.data.message;
                $scope.file={};
            }
        });
    };

    $scope.photoChanged=function(files){
     if(files.length >0 && files[0].name.match(/\.(jpeg|jpg|png)$/)){
         var file=files[0];
         var fileReader=new FileReader();
            fileReader.readAsDataURL(file);
         fileReader.onload=function(e){
             $timeout(function(){
                     $scope.thumbnail={};
                         $scope.thumbnail.dataUrl=e.target.result;
             });
         }

     }
     else{
         $scope.thumbnail={};
         $scope.message=false;
     }
 };

Directive
app.directive("fileModel",['$parse',function($parse){
      return{
              restrict:"A",
              link:function(scope,element,attrs){
                  var parsedFile=$parse(attrs.fileModel);
                  var parsedFileSetter=parsedFile.assign;

                  element.bind('change',function(){
                      scope.$apply(function(){
                            parsedFileSetter(scope,element[0].files[0]);

                      });
                  });
              }
      };

}]);

Service
//var app = angular.module('MLMApp',[]);
app.service("uploadFile",function($http){
      this.upload=function(file){
            var fd=new FormData();
            fd.append('myFile',file.upload);
            return $http.post('/upload',fd,{
                            transformRequest:angular.identity,
                            headers:{'Content-Type':undefined}
                            //headers:{'Content-Type':'multipart/form-data}
            });
      };


});



via Gurunath Bhopale

No comments:

Post a Comment