Nodejs file is undefined

Asked

Viewed 72 times

0

Hail to the people! Try to help me please, I am new in Nodejs and express and I am not able to get input file in my ejs, when I send to the route already arrives as Undefined.

File server.js

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>...

Me file of route:

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

When I take the value of req.body there is all the objects of the form but req.file always from Undefined. I’m using the connect-multiparty middleware but I’m missing something. I need the file properties contained in the file to upload to my API using form-data. Can anyone give me a hand there? Vlw

1 answer

0

You need to connect the connect-multiparty middleware in the route setting. 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" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.