Search code examples
javascriptnode.jsexpressmulter

Error downloading file to server using multer Node.js


I am trying to send an image to the server, but the server can not get this image, I do not know why this happens.

I made all the settings using the multer, however it does not work, I do not know what I'm doing wrong, could they help?

ERROR: file is undefined.

Service.js

const express = require('express');
const consign = require('consign');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const session = require('express-session');
const paginate = require('express-paginate');
const cookieParser = require('cookie-parser');
const multer = require('multer');

// const upload = multer({ dest: 'app/images/' });
const upload = multer({ dest: 'uploads/' });


const app = express();

app.set('view engine', 'ejs');
app.set('views', './app/views');

app.use(express.static('./app/public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.single('fileUploadPlease'));

// keep this before all routes that will use pagination
app.use(paginate.middleware(10, 50));

app.use(cookieParser());
app.use(expressValidator());
app.use(session({
  secret: 'asdfasjfasdf',
  resave: false,
  saveUninitialized: true,
  cookie: { expires: new Date(253402300000000) },
}));


consign()
  .include('app/routes')
  .then('config/dbConnection.js')
  .then('app/controllers')
  // .then('app/models')
  .into(app);


module.exports = app;

routes

module.exports = (application) => {
  application.get('/', (req, res) => {

  });

  application.post('/search', (req, res) => {

    console.log(`Here is the file image: ${JSON.stringify(req.file)}`);
  });
};

HTML

<!DOCTYPE HTML>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"/>
    <title>Document</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</head>
<body>
<div>
    <form class ="testeMongoose" action= "/" method= "get">
    </form>
    <div id="contain" class="container">
        <div class="col-md-12">
            <div class="card border-default mb-3">
                <form class ="testeMongoose" action= "/search" method= "post">
                    <div class="fileUpload btn btn-primary col-md-4 mb-2">
                        <span>Carrega arquivo xlsx</span>
                        <input name="fileUploadPlease" id="fileUploadPlease" type="file" class="upload" />
                    </div>
                    <div class="form-group ">
                        <div class="col-sm-10">
                            <button type="submit" class="btn btn-primary" id="Import">Enviar</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Return of req.file = undefined. I do not understand why you're wrong.


Solution

  • Your <form> doesn't set the correct encoding type:

    <form class ="testeMongoose" action= "/search" method= "post" enctype="multipart/form-data">
    

    Also, the multer documentation states: "Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate."

    So instead of app.use(upload.single(...)), this would be advisable:

    application.post('/search', upload.single('fileUploadPlease'), (req, res) => { ... })