1

Please help me out resolving this. I get empty values as result .

HTML Code

<form method="post" enctype="multipart/form-data" action="/file-upload">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="file" name="thumbnail">
    <input type="submit">
</form>

Node.js

var express = require('express');
var http = require('http');
var request = require('request');
var bodyParser = require('body-parser');    

var app = express();
app.use(express.static(__dirname + '/app/'));

// parse urlencoded request bodies into req.body
app.use(bodyParser.urlencoded({ extended: true }));

var server = app.listen(8080,function(){
 console.log("Node.js image upload");
});

app.post('/file-upload', function(req, res, next) {
 console.log(req.body);
 console.log(req.files);
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end('Success\n');
});

3 Answers 3

2

You can use npm module formidable to serve the form multipart data. The below is an example:

 app.post('/file-upload', function(req, res, next) {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    console.log('form parse');
  });

 form.on('field',function(name,value){
    console.log('in field',name,value);//gives you the field names with value
  });
  form.on('file',function(name,value){
   console.log('in file');
  });

   form.on('end', function(fields, files) {
     this.openedFiles[x].path; //gives the file path
   });
});
Sign up to request clarification or add additional context in comments.

Comments

1

body-parser can't handle multipart/form-data

You should use something like multer or busboy

handling multipart/form-data requires some complex logic, every package for handling it having a lot of settings

Comments

1

You're having problems because of enctype="multipart/form-data" in the form. You will need to install the multer package to handle those.

Basic usage is this:

//Include the package
var multer  = require('multer');
var uploadTmp = multer({ dest: 'uploads/' });

// Use a middleware to handle files
app.post('/file-upload',uploadTmp.single('thumbnail'), function(req, res, next) {

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.