Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple file upload on express js with multer returns empty array

I am building an app on Glitch with express js which requires the user to upload multiple files. Here is my code:

  var express = require('express');
var cors= require('cors');
var bodyParser= require('body-parser');
var contexts= require('./contexts');
var path= require('path');
var fileUpload= require('express-fileupload');
var multer= require('multer');
var upload = multer();

var app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(fileUpload());

app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(express.static('views/'));
//here express-fileuploads works fine
app.post('/getcontexts', function (req,res) {
   var context=contexts.get(req.files.file.data.toString());
   res.render('rast', {length: context.length, content : context});    
     });

//this is when I get an empty array 
   app.post('/getrast', upload.array('rastfiles'), function (req, res) {
  
     res.json({data: req.files});
     });

   var listener = app.listen(process.env.PORT, function () {
    console.log('SERVER STARTED ON PORT ' + listener.address().port);
   });

and here is the ejs form I use:

        <form action="/getrast" method="POST" enctype="multipart/form-data">
        <label for="rastfiles">Please select your Rast genome files with .txt extension</label>
        <br>
        <input type="file" id="file" name="rastfiles" class="inputFile" multiple>
        <br>
        <input type="submit" value="Run" id="sub">
      </form>

I already used express-fileupload to upload a single file and it worked just fine. However, when I use multer to upload multiple files I get and empty array when logging req,files into the console. Any idea why this might be happening?

I'd really appreciate any help. Thanks!

like image 889
Daniel Hernandez Avatar asked May 02 '26 16:05

Daniel Hernandez


1 Answers

The reason why multer was not working is because express-fileupload was already being used as middleware for file uploading, so commenting out this line:

  app.use(fileUpload())

fixed the problem for me.

like image 162
Daniel Hernandez Avatar answered May 04 '26 04:05

Daniel Hernandez