I’m building a portfolio site with express and i’m trying to make a dashboard to add my works from the interface but i get some errors when i try to upload files. the ejs form is encoded in multipart/form-data
//this is how multer is set up
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const workPath = `./data/works/${req.body.id}/`
fs.access(workPath, (err) => {
if (err) {
// La directory non esiste la crea
fs.mkdirSync(workPath, { recursive: true })
}
cb(null, workPath)
})
},
filename: (req, file, cb) => {
cb(null, file.originalname)
}
})
this is the post request causing the error (i guess)
it’s made to add those three files in a folder and add data and their name to a json
router.post('/addwork', auth,
upload.fields([
{ name: 'image', maxCount: 1 },
{ name: 'audio', maxCount: 1 },
{ name: 'file', maxCount: 1 }
]),
(req, res) => {
//console.log(req.body)
//console.log(req.files)
console.log(validationResult(req))
var newWorkInfo = req.body
for (const key in req.files) {
if (Object.hasOwnProperty.call(req.files, key)) {
const filename = req.files[key][0].filename
const field = req.files[key][0].fieldname
//console.log(`${filename}, ${field}`)
newWorkInfo[field] = filename
}
}
//console.log(newWorkInfo)
const worksDbPath = "./data/works.db.json"
let worksData = [];
try {
worksData = JSON.parse(fs.readFileSync(worksDbPath, 'utf8'));
} catch (err) {
console.log(err)
}
worksData.unshift(newWorkInfo)
fs.writeFileSync(worksDbPath, JSON.stringify(worksData, null, 2))
req.flash("authenticated", true)
res.redirect("/admin/dashboard")
})
this is the error i get when i try to submit the form
TypeError: path must be absolute or specify root to res.sendFile at ...PortfolioSitenode_modulesexpresslibresponse.js:442:11
the script worked for some tasks, then started to not work anymore for some reason…
Mauro Fratoni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.