Nitin Agarwal Nitin Agarwal - 5 months ago 26
AngularJS Question

How to upload any files based on their uploaded type using angular js

Is there any directives or js files to upload any format file like .ppt,.mp4,,txt,.doc .... means any kind. And also how to download those files using the angular js. Even i got some directive but no use.So,I am questioning here as, i spend a whole day to get it but in vain. Any demo will great help. So possible, help me. Thank U

Answer

Guys it very easy to upload any kind of file using the angular js. I am posting here as i take nearly a day to search and get the correct answer. Here is the proc.

  1. First inject this two files in your index.html as,

    <script src="ng-file-upload.min.js"></script>
    <script src="ng-file-upload-shim.min.js"></script>
    
  2. Now in your script.js inject the "ngFileUpload" as dependency

  3. Now write the below code from where you want to upload your file,i.e in your html file

    <form  ng-controller="MyCtrl as up" name="up.upload_form" class="form-horizontal form-label-left">
     <div class="item form-group">
                       <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Description <span class="required">*</span>
                 </label>
                       <div class="col-md-4 col-sm-6 col-xs-12">
        <input 
            type="file" 
            ngf-select 
            ng-model="up.file" 
            name="file" 
            ngf-max-size="20MB" 
            />
    
        <button type="submit" ng-click="up.submit()">submit</button>
        <p>{{up.progress}}</p></div></div>
    </form>
    
  4. In controller write,

    ZustShopController.controller('MyCtrl',['Upload','$window',function(Upload,$window){
    var vm = this;
    vm.submit = function(){ //function to call on form submit
    if (vm.upload_form.file.$valid && vm.file) { //check if from is valid
        vm.upload(vm.file); //call upload function
    }
    }
    
    vm.upload = function (file) {
    Upload.upload({
        url: 'http://serveripaddress:portnumber/upload', //webAPI exposed to upload the file
        data:{file:file} //pass file as data, should be user ng-model
    }).then(function (resp) { //upload function returns a promise
        if(resp.data.error_code === 0){ //validate success
            $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
        } else {
            $window.alert('an error occured');
        }
    }, function (resp) { //catch error
        console.log('Error status: ' + resp.status);
        $window.alert('Error status: ' + resp.status);
    }, function (evt) { 
        console.log(evt);
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
        vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
    });
    };
    }]);
    

Here server ip address is your server address and portnumber on which the server is running.

No need of service/ factories at client side

Now at server side include all requires and then add write,

     var storage = multer.diskStorage({ //multers disk storage settings
   destination: function (req, file, cb) {
       cb(null, './uploads/');
   },
   filename: function (req, file, cb) {
       var datetimestamp = Date.now();
       cb(null, file.originalname);
   }
   });

    var upload = multer({ //multer settings
               storage: storage
           }).single('file');

       /** API path that will upload the files */
      app.post('/upload', function(req, res) {
   upload(req,res,function(err){
       if(err){
            res.json({error_code:1,err_desc:err});
            return;
       }
        res.json({error_code:0,err_desc:null});
   });
     });

As simple as it is.

Note: At server side create a folder called as uploads, where all the file will be stored.

Or also you can follow the below link from where i done my code successful but with some changes. http://code.ciphertrick.com/2015/12/07/file-upload-with-angularjs-and-nodejs/

Thanks. If helpful, vote.