我想上传用户档案根据他们的学校ID
// import multer
var multer = require('multer')
// import school and student models
const { School } = require('./models/school/school.model.js')
const { Student } = require('./models/student/student.model.js')
// configure multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const dir = `./uploads/schools/${req.body.schoolId}/students`
fs.exists(dir, exist => {
if (!exist) {
return fs.mkdir(dir, { recursive: true }, error => cb(error, dir))
}
return cb(null, dir)
})
},
filename: (req, file, cb) => {
cb(null, `student-${normaliseDate(new Date().toISOString())}.${file.originalname.split('.')[file.originalname.split('.').length - 1]}`)
}
})
var upload = multer({storage: storage}).single('profile')
app.post('/student', function (req, res) {
// check if submitted school id is valid
let school = await School.findOne({ _id: req.body.schoolId })
if (!school)
return res.send(`School of id ${req.body.schoolId} doesn't exist`)
// upload the profile pic
upload(req, res, function (err) {
if (err)
return res.send(err)
})
// save the student
let newStudent = new Student({
name: req.body.name,
email: req.body.email,
school: req.body.schoolId,
profile: req.file.filename
})
const saveDocument = await newStudent.save()
if (saveDocument)
return res.send(saveDocument).status(201)
return res.send('New College not Registered').status(500)
})
null
但是当我试图在上传概要文件之前访问req.body时,我会得到一个空对象。
我会上传档案在一个tempolary文件夹,然后移动他们,但如果提交的学校id是无效的怎么办? 这将需要我删除上传的文件。 所以我想确保提交的详细信息是有效的,然后上传个人资料,稍后保存学生。
检查您的代码,您使用的是await,但找不到异步。 但它可能不是获得空req.body对象的原因。
let school = await School.findOne({ _id: req.body.schoolId })
const saveDocument = await newStudent.save()