NodeJs file is undefined

0

Save Galley! Try to help me please, I'm new to NodeJs and express and I'm not getting the input file in my ejs, when I send the route already arrives as undefined.

Server.js file

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var expressValidator = require('express-validator');
var session = require('express-session');        
var multiparty = require('connect-multiparty');

var es6Promise = require('es6-promise');
mongoose.Promise = es6Promise.Promise;
//URI: MLab    
mongoose.connect('mongodb://xxxx:[email protected]:14658/users');

app.set('view engine', 'ejs');
app.set('views', './app/views/');
app.use(express.static('./app/public'));

//Middlewares
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(multiparty());

app.use(function(req, res, next){
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    res.setHeader("Access-Control-Allow-Headers", "content-type");        
    res.setHeader("Access-Control-Allow-Credentials", true);

    next();
});

My HTML:

<form method="POST" action="/publish" encrypt="multipart/form-data">
            <!-- <form method="POST" action="/publish" ectype="multipart/form-data"> -->
            <div class="panel-body">
                <div class="form-group">
                    <span>Imagem</span>
                    <input type="file" name="img" id="img" class="form-control">
                </div>...

I route file:

app.post('/home/comment', function (req, res) {                        
    console.log(req.body);
    console.log(req.files);
    homeController.addComment(req, res);
});

When I get the value of the req.body there are all the objects of the form but the req.file always gives undefined. I'm using the connect-multiparty middleware but I'm missing something. I need the file properties contained in file to upload to my API using form-data. Can somebody help me out there? Vlw

    
asked by anonymous 01.05.2018 / 02:40

1 answer

0

You need to connect the connect-multiparty middleware in the route definition. Try the following:

var multipart = require('connect-multiparty');
var path = require('path');
var multipartMiddleware = multipart({
    uploadDir : path.join(__dirname,'../public/images')
});

app.post('/upload', multipartMiddleware, function(req, res, next) {
  console.log(req.body, req.files);
  // don't forget to delete all req.files when done
  res.status(200).json({message: "file uploaded"});
});

And in your form:

<form action="/upload" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
    
03.05.2018 / 16:38