I'm having trouble uploading files using formidable. I'm on Windows server 2016.
My code, which in its entirely is shown below, is based on https://www.geeksforgeeks.org/how-to-upload-file-using-formidable-module-in-node-js/
const express = require('express');
const fs = require('fs');
const path = require('path')
const formidable = require('formidable');
const app = express();
app.post('/api/upload', (req, res, next) => {
const form = new formidable.IncomingForm(
{ uploadDir: __dirname + '\\tmp', keepExtensions: true }
);
form.parse(req, function(err, fields, files){
var oldPath = files.profilePic.path;
var newPath = path.join(__dirname, 'uploads')
+ '/'+files.profilePic.name
var rawData = fs.readFileSync(oldPath)
fs.writeFile(newPath, rawData, function(err){
if(err) console.log(err)
return res.send("Successfully uploaded")
})
})
});
app.listen(3000, function(err){
if(err) console.log(err)
console.log('Server listening on Port 3000');
});
I use Postman to send a file.
When triggering the /api/upload API, the file sent is correctly placed in the tmp folder, but reading the path is when the problem arise:
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
This message points to fs.readFileSync(oldPath).
console.log('files='+files) returns files=[object Object]
console.log('files.profilePic='+files.profilePic) returns
C:\somepath\node_modules\formidable\src\PersistentFile.js:50
return `PersistentFile: ${this._file.newFilename}, Original: ${this._file.originalFilename}, Path: ${this._file.filepath}`;
^
TypeError: Cannot read properties of undefined (reading 'newFilename')
at PersistentFile.toString (C:\somepath\node_modules\formidable\src\PersistentFile.js:50:42)
All 4 referenced modules exist in node_modules folder.
Simply change
var oldPath = files.profilePic.path;
to
var oldPath = files.profilePic.filepath;
Also make sure that you create the "uploads" folder as the code doesn't create it and it will fail without it.
EDIT: A side note is that if your environment is just spitting out [object object] when you console log an object, then probably get a new environment (visual studio code is good) that gives useful information.
I know it is an old question, but since a few tutorials I've seen still have the same code or similar code to the above, I guess formidable has chnaged his api, so the above code does not work any more. With formidable v3.5.1 files.profilePic is an array, therefore to access filepath we have to use files.profilePic[0].filepath
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With