Home > Enterprise >  How to use express-uploadfiles?
How to use express-uploadfiles?

Time:12-17

I want to print the name of a file to the console, but it gives me an error: when I post the path of my server with the file

TypeError: Cannot read properties of undefined (reading 'file')

my code is:

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");

// SETTINGS
app.set("port", process.env.PORT || 3000);

// MIDDLEWARES
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
    console.log(`${req.method} - ${req.url}`);
    next();
});

// ROUTES
app.post("/upload", (req, res) => {
    const file = req.files.file;
    console.log(file.name);
});

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

CodePudding user response:

You're not using the fileUpload middlewere. Its the middlewere that adds the files to the request method.

app.use(fileUpload())

Add this before the upload handler, in the same way you use the bodyParser middlewere.

To upload files you also need to make sure that the html form uses

encType="multipart/form-data"

You can check out the documentation: https://github.com/richardgirges/express-fileupload

It also has basic code examples: https://github.com/richardgirges/express-fileupload/tree/master/example#basic-file-upload

  • Related