Search code examples
node.jspostmanmulter

How to get the file and upload it using Node.js and Postman


I need one help. I am sending file using Postman and I need to upload it inside required folder using Node.js. I am explaining my code below.

server.js:

var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var session = require('express-session');
var app=module.exports=express();
var server=http.Server(app);
var port=8889;
var api=require('./api/api.js');
app.use(express.static(__dirname + '/public'));     // set the static files location /public/img will be /img for users
app.use(morgan('dev'));                     // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' }))    // parse application/x-www-form-urlencoded
app.use(bodyParser.json({limit: '5mb'}))    // parse application/json
app.use(methodOverride());    
app.post('/upload',api.upload);    
server.listen(port);
console.log("Server is running on the port"+port);

api.js:

var multer  = require('multer');
var storage =multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './../uploads');
  },
  filename: function (req, file, callback) {
    callback(null, Date.now()+'-'+file.originalname);
  }
});
var upload = multer({ storage: storage});
exports.upload=function(req,res){
}

Actually I am posting the file using postman whose screen shot is given below.

enter image description here

Here my requirement is the file will upload into the required folder i.e-uploads and the uploaded file name will return as response to user. Please help me.


Solution

  • You haven't actually used the multer here. You have created upload using multer but you did not use it.

    Try the following code:

    app.post('/upload', upload.single('file'), function (req, res, next) { 
         // req.file is the `file` file
         // req.body will hold the text fields, if there were any
    })
    

    where upload will be the var upload = multer({ storage: storage}); variable.