To fix the ‘req.files undefined’ error in our Express app when we try to add file upload feature into our Express app, we should add a file upload handling library into our Express app.
For instance, we can use the express-fileupload
library by installing it with:
npm i express-fileupload
Then we can use the library by writing:
const express = require('express')
const app = express()
const port = 3000
const fileupload = require("express-fileupload");
app.use(fileupload());
app.post("/", (req, res) => {
if (!req.files) {
res.send("File was not found");
return;
}
const file = req.files.file;
res.send(`${file.name} File Uploaded`);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
we add the fileUpload
middleware with:
const fileupload = require("express-fileupload");
app.use(fileupload());
Now the uploaded file can be accessible from the req.files
object.
file
is the key of the form data that has the file as its value.
And we can get the name of the file with the file.name
property.
One reply on “How to Fix the ‘req.files undefined’ Error with Express?”
It works for me but the only problem am having is that i need to call the (file.path) or (file.tempFilePath) . The result i get from that request is ‘undefined’ or ‘null’ from calling req.files.file.tempFilePath / req.files.file.path