problems in form with input text and input file

2

I'm doing a project that requires a form with several input text fields and an input file, and something very curious happens to me and I just give the attribute enctype="multipart/form-data" to the form, the input text data are not sent in the body of the request. I have problems with this topic

I am using express-formidable and formidable to upload the file, the files process it well, but I need the data from the other fields. I stress that when I remove the property enctype="multipart/form-data" to the forms, the data of the input text fields are sent correctly in the body of the request but I can not upload the file of the

app.js file

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var formidable = require('express-formidable');



var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
app.use(formidable({
  encoding: 'utf-8',
  uploadDir: __dirname+'/public/images',
  keepExtensions: true,
  multiples: true, // req.files to be arrays of files 
})
)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

index.jade file

extends layout

block content
    h1=title
    form.mi-form(action="/f1" method="post" name="f1" )
        div nombre
        input(type="text" name="titulo")
        input(type="file" name="archivo")
        input(type="submit" value="enviar")

index.js file

var express = require('express');
var router = express.Router();



/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.post('/f1', function(req, res, next) {
    console.log(" --- esto es el cuerpo de la solicitud --- ");
    console.log(req.body);
    console.log(req.files);

  res.render('index', { title: req.body.titulo });
});
module.exports = router;

With this configuration, I do not upload the files, but the input text is sent in the body of the request as seen in the following image.

[! [Web browser] [1]] [1] [! [console] [2]] [2]

Now let's make some small modification in the form, placing the enctype="multipart/form-data" and let's see what happens.

index.jade extends layout

block content
    h1=title
    form.mi-form(action="/f1" method="post" name="f1" enctype="multipart/form-data" )
        div nombre
        input(type="text" name="titulo")
        input(type="file" name="archivo")
        input(type="submit" value="enviar")

and this is the result that gives

[! [Web browser] [1]] [1]

We can see that the data was not sent in the body of the request What would be the problem?

Let's make another modification a little bigger:

Let's use express-formidable

app.js

 var express = require('express');
 var path = require('path');
 var favicon = require('serve-favicon');
 var logger = require('morgan');
 var cookieParser = require('cookie-parser');
 var bodyParser = require('body-parser');
 var formidable = require('express-formidable');



var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
app.use(formidable({
  encoding: 'utf-8',
  uploadDir: __dirname+'/public/images',
  keepExtensions: true,
  multiples: true, // req.files to be arrays of files 
})
)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

This is the result:

[! [Web browser] [1]] [1]

Those are the mistakes that I do not understand that may be happening, who can explain me I appreciate it. In the documentation of express-formidable or formidable say something of these errors

  [1]: https://i.stack.imgur.com/8Cj4R.jpg
  [2]: https://i.stack.imgur.com/ShoVB.jpg
    
asked by Daniel Enrique Rodriguez Caste 20.12.2016 в 02:28
source

1 answer

2

try Multer is to upload files on the server or in a cloud, I give you an example as I have done uploading on the server.

formular.html

 <form action="/newimagect" enctype="multipart/form-data" method="post" id="imgct" class="columinput">
   <h2>Nuevo imagen</h2>
   <input type="text" id="idr" name="idr" required style="display:none;" />
   <label for="gimg"></label>
   <input type="file" id="gimg" name="gimg" required />
   <div id="txA"></div>
   <input type="submit" value="Ingresar" id="nvig" />
 </form>

images.js

 $(inicio_pagina);

 function inicio_pagina () {
    $("#nvig").on("click", subirimage);
 }

 function subirimage () {
   var idob=$("#idr").val()
   var ctimg=$("#gimg")[0].files[0]
   var namectimg=ctimg.name;
   var extectimg=namectimg.substring(namectimg.lastIndexOf('.')+1);
   if (idob=="") {
    $("#txA").text("Id de contenido no disponible")
    return false
   }
   else{
    if (!es_imagen(extectimg)) {
      $("#txA").text("tipo de imagen no permitido")
      return false
    }
    else{
      var formu=new FormData($("#imgct")[0])
      $.ajax({
        url: '/newimagect',
        type: 'POST',
        data: formu,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend:function () {
            $("#txA").prepend('loading');
        },
        success:relimgcont,
        error:function () {
          console.log('error');
        }
       })
       return false
    }
   }
 }

 function relimgcont (res) {
   console.log(res);
 }

app.js

var express=require("express")
var bodyparse=require("body-parser")
var path=require("path")
var multer=require("multer")

var port = process.env.PORT || 3000

var app=express()

var rutimage=path.join(__dirname,"..","public/images/contenido/")

var storage=multer.diskStorage({
  destination:function (res,file,cb) {
    cb(null,rutimage)
  },
  filename:function (res,file,cb) {
    cb(null,Date.now()+file.originalname)
  }
})

var upload=multer({storage:storage})

app.use(express.static(path.join(__dirname,"public")))

app.use(bodyparse.urlencoded({extended: false}))
app.use(bodyparse.json())

app.post("/newimagect",upload.single("gimg"),function (req,res) {
  var id=req.body.idr
  var image=req.file.filename
})

servidor.listen(port,function () {
  console.log("servidor en "+port)
}
    
answered by 20.12.2016 / 18:14
source