I'm encountering a problem when I want to upload a file to 'public' folder. This problem occurs when I don't use './'
. if I use '../'
or '/'
files do not upload to the public folder.
**controllers.js**
files.forEach(file => {
file.mv('../public/' + file.name, err => {
if (err) {
log({ err });
return res.redirect('/')
}
log('file uploaded');
})
})
Error: Error: ENOENT: no such file or directory, open 'D:\Users\Antonio\Desktop\public\image4.jpg'
And also this error: Express-file-upload: Request is not eligible for file upload!
This happens when I'm inside controllers/controllers.js
. If I write this code inside app.js
, I do not face any issues.
The file.mv()
method works relative to the cwd
current working directory path.
To let it work, you need to write like:
const path = require('path')
const fileName = path.join(__dirname, '../public/', file.name)
file.mv(fileName)
By doing so, the path will be relative to the controller.js
file (and not relative to the cwd
)