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.