I have a problem with nodejs, when I want to make a post with an image, I have an error message "Cannot read property 'filename' of undefined" I do not see where my error is. this is my multer :
app.use(express.static('views/images'))
const storage = multer.diskStorage({
destination: 'views/images',
filename: function(req,file, cb){
cb(null, file.fieldname + '_'+ Date.now()+path.extname(file.originalname));
}
})
const upload = multer({storage: storage}).single('img');
here is my database.js
db.run(`
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
description TEXT,
image TEXT
)
`)
exports.uploadPost = function(name, description, Filename, callback){
const query = "INSERT INTO products('name', 'description', 'image') VALUES (?,?,?)"
const values = [name, description, Filename]
db.run(query,values, function(error){
callback(error)
})
}
and app.js
app.post('/products/create', (req,res) => {
// req.file contains information of uploaded file
// req.body contains information of text fields, if there were any
upload(req, res, (err) => {
const name = req.body.name
const description = req.body.description
const Filename = req.file.filename
db.uploadPost(name, description, Filename, function(error){
console.log(req.Filename)
const id = this.lastID
res.redirect('/products/'+id)
})
})
})
and HTML
<form action="/products/create" method="POST">
<div>
<label class="form-label" for="img">Select image:</label>
<input class="form-input" type="file" id="img" name="img" required>
</div>
</form>
添加 enctype="multipart\/form-data"
<form action="/products/create" method="POST" enctype="multipart/form-data">
<div>
<label class="form-label" for="img">Select image:</label>
<input class="form-input" type="file" id="img" name="img" required>
</div>
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.