https://github.com/expressjs/multer/
you can upload file with multer middleware
<form action="http://localhost:3000/upload" method="POST" enctype="multipart/form-data">
<input type="hidden" name="pdselected" value="0">
<input type="text" name="pdname" placeholder="name"><br>
<input type="text" name="pddesc" placeholder="desc"><br>
<input type="number" name="pdprice" placeholder="price"><br>
<input type="text" name="pdcolor" placeholder="color"><br>
<input type="text" name="pdcate" placeholder="cate"><br>
<input type="file" name="avatar" multiple="multiple">
<input type="submit" value="click">
</form>
npm install multer --save
and then use multer
var multer = require("multer");
var upload = multer({dest:"uploads/"});
for one image
app.post("/upload",upload.single('avatar'),function(req,res,next){
})
for multiple image
app.post('/uploads',upload.array('avatar',2),function(req,res,next){
})
for no file
app.post('/uploads',upload.none(),function(req,res,next){
})
var pdSchema = mongoose.Schema({
selected:String,
name:String,
price:Number,
desc:String,
img:String,
color:String,
cate:String
});
app.post("/upload",upload.array('avatar',2),function(req,res){
console.log(req.files);
var imgDist = [];
req.files.map(function(item){
imgDist.push(item.filename);
});
var pdDetail =new pd({
selected:req.body.pdselected,
name:req.body.pdname,
desc:req.body.pddesc,
price:req.body.pdprice,
color:req.body.pdcolor,
cate:req.body.pdcate,
img:imgDist.toString()
});
console.log(pdDetail)
pdDetail.save(function(err,doc){
if(err){
console.log(err);
}else{
// res.json({"code":0,"data":doc});
res.sendFile(__dirname+"/upload.html");
}
})
})
Question: file extension
https://github.com/expressjs/multer/issues/170
reference:
https://stackoverflow.com/questions/36477145/how-to-upload-image-file-and-display-using-express-nodejs
https://developer.mozilla.org/zh-CN/docs/learn/Server-side/Express_Nodejs/mongoose
**
Addditional
you can use https://www.npmjs.com/package/formidable
**