我想通过multer上传图片,但首先我想为每个用户创建一个目录或文件夹,然后将图片上传到该用户文件夹。
如果我自己为用户创建文件夹并上传,则传递user_id
,图像会上传到该文件夹中。
但如果我通过代码完成,我就无法做到。
当我在目的地时,我正在添加req.body.user_id
,它会给我undefined
。
像这样 :-
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/images/'+ req.body.user_id)
}
[
app.post('/test', function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + '/images/' )
},
filename: function (req, file, cb) {
cb(null, file.originalname + '-' + Date.now())
//console.log(file);
}
});
var upload = multer({ storage: storage }).single('image');
var formatted = new Date().toLocaleString();
upload(req, res, function (err) {
var data = {
"user_id": req.body.user_id,
"item_id": req.body.item_id,
"sell_type": req.body.sell_type,
"sell_name": req.body.sell_name,
"sell_location": req.body.sell_location,
"sell_price": req.body.sell_price,
"data_post": formatted
};
console.log("error ==>",err);
if(err){
res.status(400).json({
"status_code": 'ERROR',
"message": "image uploadinf Fail"
});
}else{
fs.exists("/var/www/html/Anoop/nodetest/images/" + data.user_id, (exists) => {
console.log(exists);
if(exists) {
res.status(200).json({
"status_code": "SUCCESS",
"message": "uploaded",
"data": req.file.path
});
}
else
{
mkdirp("/var/www/html/Anoop/nodetest/images/" + data.user_id, function (err, result) {
if (err) {
res.status(400).json({
"status_code": "ERROR",
"message": "dir not created"
});
} else {
//console.log(result);
res.status(200).json({
"status_code": "SUCCESS",
"message": "dir created",
"data": req.file.path
});
}
});
}
});
}
});
});
]
答案 0 :(得分:1)
试试此代码
const fs = require('fs')
const filesDir = 'files';
// check if directory exists
if (!fs.existsSync(filesDir)) {
// if not create directory
fs.mkdirSync(filesDir);
}