Receiving Multipart form data in node js

Viewed 2877

I am trying to send multipart form-data from postman to my nodejs restify server. But the request.files is coming undefined.

Below is my code and a screenshot from my postman.

//Code

var restify = require('restify');
var os = require('os');


var server = restify.createServer({
    name: 'New App',
    version: '1.0.0'
});

server
    .use(restify.acceptParser(server.acceptable))
    .use(restify.fullResponse())
    .use(restify.bodyParser({mapParams: true, 
        mapFiles: true,
        keepExtensions: true,
        uploadDir: os.tmpdir()
    }));

server.post({path: '/api/image', version: '1.0.0'},controllers.image.addImage);

exports.addImage = function (req, res, next) {

    console.log("Files : "+req.files);
}

OutPut :

Files : undefined

screenshot :

https://i.stack.imgur.com/0hTX0.png

2 Answers

Simply use : https://www.npmjs.com/package/multi-part-form-data-upload It automatically parse files and another type of multipart data:

// Express
const uploader = require('multi-part-form-data-upload')(options /* config options */ );
const app = express();

app.post('/uploads',uploader, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ body: req.body }));
});

//  OR Http

const http = require('http');
const uploader = require('multi-part-form-data-upload')(options /* config options */ );

const server = http.createServer(async (req, res) => {
  if (req.url === '/uploads' && req.method.toLowerCase() === 'post') {
    await uploader(req, res, () => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ body: req.body }));
    });
    return;
  }
}
Related