Uploading a file with express-fileupload doesn't work

3.6k views Asked by At

I'm attempting to upload a file with express-fileupload (express-fileupload) in Node js. But I wasn't successfully yet.

My app.js (where my express server is running) looks like this:

const express = require('express');
const exphbs = require('express-handlebars');
const fileUpload = require('express-fileupload');

const app = express();
const port = 5000;

app.use(fileUpload({
  debug: true
}));

app.use(express.static('./upload'));

const routes = require('./server/routes/task');
app.use('/', routes);

app.listen(port, () => console.log(`Listening on port ${port}`));

My task.js (where my routes are) looks like this:

const express = require('express');
const router = express.Router();
const taskController = require('../controllers/taskController');

router.post('/admin/fileUpload', taskController.fileUpload);

module.exports = router;

My taskController.js (where my routes are getting controlled) looks like this:

exports.fileUpload = (req, res) => {

  let sampleFile;
  let uploadPath;

  if (!req.files || Object.keys(req.files).length === 0) {
    res.render('admin', { error: `No files were uploaded!` });
  } else {
    sampleFile = req.files.sampleFile;
    uploadPath = __dirname + '/upload/' + sampleFile.name;
    sampleFile.mv(uploadPath, function (err) {
      if (err) throw err;
      res.render('admin', { alert: `File ${sampleFile.name} successfully uploaded!` });
    }
  }
}

My admin.hbs (I'm also using express-handlebars) looks like this:

<form method="POST" action="/admin/fileUpload">
  <h2>Upload File</h2>
  <input type="file" enctype="multipart/form-data" name="sampleFile">
  <button type="submit">
</form>

So, my log looks like this when I start the express server:

[nodemon] starting `node app.js`
Listening on port 5000
Express-file-upload: Request is not eligible for file upload!

I'm trying to find the issue for hours but haven't had any luck yet.

1

There are 1 answers

0
Lukas Keller On BEST ANSWER

So, it took me a while but I found my issue.

I've made a two little mistakes in my form and in my upload path.

<form method="POST" action="/admin/fileUpload">
 <h2>Upload File</h2>
 <input type="file" enctype="multipart/form-data" name="sampleFile">
 <button type="submit">
</form>

Thats wrong. I've added the "enctype" in the wrong place. It should be in the form and not in the input field.

Solution for my form:

<form method="POST" action="/admin/fileUpload" enctype="multipart/form-data">
 <h2>Upload File</h2>
 <input type="file" name="sampleFile">
 <button type="submit">
</form>

Solution for my upload path:

Instead of

uploadPath = __dirname + '/upload/' + sampleFile.name;

I need to do this

uploadPath = './upload/' + sampleFile.name;