我正在尝试将上传的文件名保存到数据库中?谢谢。基本上我怎样才能将 multer 传递file.name
到数据库中。我的尝试是使用这个变量:var fileimage = file.name;
router.use(multer({ // https://github.com/expressjs/multer
dest: './uploads/',
limits : { fileSize:100000 },
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase();
},
onFileUploadData: function (file, data, req, res) {
// file : { fieldname, originalname, name, encoding, mimetype, path, extension, size, truncated, buffer }
var params = {
Bucket: 'lemybucket01',
Key: file.name,
Body: data
};
s3.putObject(params, function (perr, pres) {
if (perr) {
console.log("Error uploading data: ", perr);
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
},
onFileUploadComplete: function (file) {
var fileimage = file.name;
}
}));
router.route('/')
//POST a new prod
.post(function(req, res) {
if(req.files.fileimage !== undefined){ // `image` is the field name from your form
//res.redirect("/uploads"); // success
}else{
res.send("error, no file chosen");
}
// Get values from POST request. These can be done through forms or REST calls. These rely on the "name" attributes for forms
var username = req.body.username;
//call the create function for our database
mongoose.model('Prod').create({
username : username,
fileimage : fileimage
}, function (err, prod) {
if (err) {
res.send("There was a problem adding the information to the database.");
} else {
//Prod has been created
console.log('POST creating new prod: ' + prod);
res.format({
//HTML response will set the location and redirect back to the home page. You could also create a 'success' page if that's your thing
html: function(){
// If it worked, set the header so the address bar doesn't still say /adduser
res.location("prods");
// And forward to success page
res.redirect("/prods");
},
//JSON response will show the newly created prod
json: function(){
res.json(bloprodb);
}
});
}
})
});