Best practice to Upload file to the Server using AngularJS and NodeJS
Posted By : Rahul Sarkar | 10-Jun-2017
Here I am going to describe you the best practice to upload file to the server using Angular and Node JS.
First we have to create a input box in HTML to select the file.
Then we have to write code in angular to create the request to upload.
var uploadUserFile = function(file) { var uploadFileUrl = "/api/v1/upload/; var uploadFile = Upload.upload({ url: uploadFileUrl, file: file }); }
Now set the router path to call the download function of backend
router.post('/api/v1/upload/', FileUploadController.saveFile);
Now create a controller in Node:
var UploadService = require("uploadService").UploadService; module.exports.CompanyPoliciesController = (function() { var saveFile = function(req, res) { UploadService.saveFile(req.files.file, res); } return { saveFile: saveFile }; })();
Now create service method to upload your file to the server:
module.exports.UploadService = (function() { var uploadCompanyPolicyFileToServer = function(file, res) { var fs = require('fs'); var path = require('path'); // to create a path seperator var mkdirp = require('mkdirp'); // to create directory var uuid = require('node-uuid'); var filePath = '/opt/userFiles/'; mkdirp(filePath, function (err) { if (err) { configurationHolder.ResponseUtil.responseHandler(res, err, err.message, true, 400); } else { var target_path = filePath + file.originalFilename, tmp_path = file.path; var source = fs.createReadStream(tmp_path); var dest = fs.createWriteStream(target_path); source.pipe(dest); source.on('end', function(err) { if (err) { configurationHolder.ResponseUtil.responseHandler(res, err, "failed to upload " + file.name, true, 400); } else { configurationHolder.ResponseUtil.responseHandler(res, {}, File upload successfully, true, 400); } }); } }); } return { saveFile: saveFile } })();
Thank You !!!
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rahul Sarkar
Rahul is an intellectual web app developer, he has good knowledge of C, Java, Java Script, Jquery. Apart from this he likes to travel and explore new places.