1

Client side:

I have done file upload with AngularJS and NodeJS it's working but while uploading file i need to pass 'name' and 'email' to server.

Server side:

After uploading file into folder i need to save file path, name and email into database. How can i do this?

angular.module('fileUpload', ['ngFileUpload'])
.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) {
		
		console.log(vm.name);
		console.log(vm.email);
		
		
        Upload.upload({
            url: 'http://localhost:3000/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
        });
    };
}]);
<script src="http://cdn.bootcss.com/danialfarid-angular-file-upload/12.2.13/ng-file-upload-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/2.4.1/angular-file-upload.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
	<head>
		<title>Home</title>
	</head>
	<body ng-app="fileUpload">
		<h1>Angular Node File Upload</h1>
        <form  ng-controller="MyCtrl as up" name="up.upload_form">
               
			name	
			<input type="text" ng-model="up.name"><br> <br>
			email	
			<input type="text" ng-model="up.email"><br> 
			Image 
            <input 
                type="file" 
                ngf-select 
                ng-model="up.file" 
                name="file" 
                ngf-max-size="20MB" 
                />
            Image thumbnail: <img style="width:100px;" ng-show="!!up.file" ngf-thumbnail="up.file || '/thumb.jpg'"/>
            <i ng-show="up.upload_form.file.$error.required">*required</i><br>
            <i ng-show="up.upload_form.file.$error.maxSize">File too large 
            {{up.file.size / 1000000|number:1}}MB: max 20M</i>
           <!--  Multiple files
            <div class="button" ngf-select ng-model="up.files" ngf-multiple="true">Select</div>
            Drop files: <div ngf-drop ng-model="up.files" class="drop-box">Drop</div> --><br> 
            <button type="submit" ng-click="up.submit()">submit</button>
            <p>{{up.progress}}</p>
        </form>
	</body>
	
</html>

Backend code:

var express = require('express'); 
var app = express(); 
var bodyParser = require('body-parser');
var multer = require('multer');

app.use(function(req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Allow-Origin", "http://localhost");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/** Serving from the same express Server
No cors required */
app.use(express.static('../client'));
app.use(bodyParser.json());  

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.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
    }
});

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

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

app.listen('3000', function(){
    console.log('running on 3000...');
});

i tried like this

Upload.upload({
        url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
        data:{file:file, name:vm.name, email:vm.email} //pass file as data, should be user ng-model
    })

backend

app.post('/upload', function(req, res) {
        console.log(req.body);
        console.log(req.file);
      upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
             res.json({error_code:0,err_desc:null});
        });
    });

in front end(angular)i am getting value what ever i entered in form but backend(nodejs) i am getting undefined value enter image description here enter image description here

1
  • Are you using Cloudinary for file upload, also can we see your upload method Commented Jan 10, 2017 at 13:02

3 Answers 3

1

You need to amend your angular code to send the extra info in the data of the request

Upload.upload({
        url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
        data:{file:file, name:vm.name, email:vm.email} //pass file as data, should be user ng-model
    })

Then in your backend code you can reference this on the body of the request

req.body.name
req.body.email
Sign up to request clarification or add additional context in comments.

4 Comments

i am getting undefined in my console(backend)
sorry should be vm.name and vm.email. changed my answer
yeah i modified still i am getting undefined only
can you please help me out
0

I not sure if my answer will help you. But you can add in your data the name and the email.

Upload.upload({
            url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
            data:{file:file,name:"putHeretheName",email:"putHereTheMail"} //pass file as data, should be user ng-model
        }

Then server side you can create a function or complete your actual "/upload" with a query that save in your bdd what you want. You just have to get the name of the path created and then do the save in case of your upload is successful.

Maybe this e.g will help you more: https://www.npmjs.com/package/ng-file-upload

8 Comments

can you please help me out
I never used the lib multer, so I need more description to try to help you. Cause my link explain how to do what you want and if you say it's doesn't work, I need more info about the error.
i followed this tutorial code.ciphertrick.com/2015/12/07/…
So did you tried to put the name and the email inside you data that you will send to your server ?
server side i am getting value undefined
|
0

You can add a file property that will hold the file and update the data property to contain email and name inside the Upload.upload object. This way you can get them easily at the server side.

Note: I have updated my answer, I wrapped all the values Angular viewis emitting inside a params object. I also changed angular-ng-upload CDN wasn't working on codepen. You should also load Angular.js first.

view

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload-shim.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload.js"></script>
<html>
    <head>
        <title>Home</title>
    </head>
    <body ng-app="fileUpload">
        <h1>Angular Node File Upload</h1>
        <form  ng-controller="MyCtrl as up" name="up.upload_form">

            name    
            <input type="text" ng-model="up.params.name"><br> <br>
            email   
            <input type="text" ng-model="up.params.email"><br> 
            Image 
            <input 
                type="file" 
                ngf-select 
                ng-model="up.params.file" 
                name="file" 
                ngf-max-size="20MB" 
                />
            Image thumbnail: <img style="width:100px;" ng-show="!!up.params.file" ngf-thumbnail="up.params.file || '/thumb.jpg'"/>
            <i ng-show="up.upload_form.params.file.$error.required">*required</i><br>
            <i ng-show="up.upload_form.params.file.$error.maxSize">File too large 
            {{up.params.file.size / 1000000|number:1}}MB: max 20M</i>
           <!--  Multiple files
            <div class="button" ngf-select ng-model="up.files" ngf-multiple="true">Select</div>
            Drop files: <div ngf-drop ng-model="up.files" class="drop-box">Drop</div> --><br> 
            <button type="submit" ng-click="up.submit()">submit</button>
            <p>{{up.progress}}</p>
            <p>{{up.params}}{{up.params.file.size}}</p>
        </form>
    </body>

</html>

Angular

var vm = this;

vm.submit = function(){ 
   if (vm.upload_form.file.$valid && vm.params.file) {
       console.log(vm.params)
       vm.upload(vm.params); // Pass the `vm.params` object.
   }
 }

vm.upload = function (params) {

    console.log(params.name); // params.name should be available
    console.log(params.email); // params.email should be available
    console.log(params.file); // params.file should be available

    Upload.upload({
      url: 'http://localhost:3000/upload',
      file: params.file,   // Image to upload
      data: {
        name: params.name,
        email: params.email
      } 
    })
}

Node.js/express

app.post('/upload', function(req, res) {
    console.log(JSON.parse(req.body.data)); // email and name here
    console.log(req.files.file); // file object

    upload(req,res,function(err){
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }
         res.json({error_code:0,err_desc:null});
    });
});

8 Comments

req.body.data m getting undefined
i am getting like this {}
The Angular part can you log the form object that you are getting before making the API call
angular i got value but in server side i am getting undefined
You paste a pseudo code of what you get from the angular view here
|

Your Answer

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