Full Stack Solutions
node js upload image

How to upload an image using Node js Angular Js and multer with image preview – 2

How to upload an image using Node js Angular Js and multer with image preview – 2

This is the second part of the File/Image Uploading to the server using Node JS.You can use
the PHP Storm or Sublime Text as IDE.We have following npm packages.

  • Multer
  • Express
  • body-parser
  • fs

Dev Dependencies :

  • gulp-jshint
  • gulp-develop-server
  • gulp-jshint

You can download the both Client & Server Code : github

Create App.js Node Application

You can create an Empty Node JS Application by

http.createServer(function (request, response) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body as "Hello World"
   response.end('Hello Worldn');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Here We use the http instance by calling the createServer method to create the server instance and
then we bind it to the 8081 Port.

You can test application by “node app.js”

Set up Dependencies in package.json

package.json

{
  "name": "expapp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "3.9.0",
    "gulp-develop-server": "0.5.0",
    "gulp-jshint": "1.12.0"
  },
  "dependencies": {
    "body-parser": "1.14.1",
    "express": "4.13.3",
    "fs": "0.0.2",
    "multer": "1.1.0"
  }
}

You can install it by npm install

Instantiating of Dependencies :

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

Allowing Cross Origin Requests from localhost

  app.use(function(req, res, next) { 
        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();
    });

You can use express.static url for the client if you are serving from the same Express Server.

app.use(express.static('../client'));

Multer Storage Setting by setting the path for the Images after uploading and also having a unique file name “file.fieldname” is the field : file,file.originalname is the original name of the file that’s is being uploaded.

Each file contains following information :

fieldname: Field name specified in the form.
originalname: Name of the file on the user’s computer.
encoding: Encoding type of the file.
mimetype: Mime type of the file.
size: Size of the file in bytes.
destination: The folder to which the file has been saved.
filename: The name of the file in the destination.
path: The full path to the uploaded file.
buffer: A Buffer of the entire file.

var storage = multer.diskStorage({
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]);
}
});

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

Conclusion

Now you can run your application by starting the server node server.js on the command prompt and after then goto
http://localhost:8000.

uploading

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular