使用猫鼬上传和检索图像时出错?

时间:2020-08-20 18:58:58

标签: node.js express mongoose ejs multer

如以下代码所示,我正在使用具有快速,主体解析器和ejs模板的节点js框架。但是上传jpg文件时出现错误。如何在内容类型中添加jpeg和gif?还有一个问题,用户不必上传图像。如果他当时未上传,则此代码也会显示错误。

const examSchema = new mongoose.Schema({
topic: String,
examdate: Date,
duration: String,
time: String,
totalquestions: Number,
attendance: Number,
questions:
     [
       {
         question: String,
         uploadedimg:
         {
           data: Buffer,
           contentType: String
         },
         options: {
           option1: String,
           option2: String,
           option3: String,
           option4: String,
           answer: String
         }
       }
     ],   ranklist: [] });
 
 const Exam = mongoose.model("Exam", examSchema);
 
 const storage = multer.diskStorage({   destination: (req, file, cb) =>
 {
     cb(null, 'uploads')   },   filename: (req, file, cb) => {
     cb(null, file.fieldname + '-' + Date.now())   } });
 
 
 const upload = multer({ storage: storage });
    
 app.post("/addquestions", upload.single('image'), function (req, res) { 
     const addBtn = req.body.addBtn;     

 const ques = {
   question: req.body.question,
   uploadedimg: {
     data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
     contentType: 'image/png'    // how can I add jpeg and also gif here ?
   },
   options: {
     option1: req.body.option_1,
     option2: req.body.option_2,
     option3: req.body.option_3,
     option4: req.body.option_4,
     answer: req.body.answer
   }
 }
  });

0 个答案:

没有答案