Node.js 使用node js和mongoose在restapi中上传图像和PDF

Node.js 使用node js和mongoose在restapi中上传图像和PDF,node.js,mongodb,mongoose,restapi,Node.js,Mongodb,Mongoose,Restapi,我曾尝试使用node js REST API将一些数据插入mongodb数据库,但我遇到了一个错误意外字段我是node的新手,请帮助我白皮书是我的pdf文件,如果我只上传标题、描述和图像等数据,它会给出正确答案,状态代码为201,但我尝试上传所有数据和pdf,但会给出错误 型号代码: description: { type: String, required: true }, imgURL: { type: String,

我曾尝试使用node js REST API将一些数据插入mongodb数据库,但我遇到了一个错误意外字段我是node的新手,请帮助我白皮书是我的pdf文件,如果我只上传标题、描述和图像等数据,它会给出正确答案,状态代码为201,但我尝试上传所有数据和pdf,但会给出错误

型号代码:

    description: {
      type: String,
      required: true
    },
    imgURL: {
      type: String,
      required: true
   },
   whitePaperLink: {
      type: String,
      required: true,
                
   },
app.js文件

app.use('/whitePaper', express.static('whitePaper'));
路由器文件

const whitePaperLink = multer.diskStorage({
 destination: './whitePaper/',
 filename: (req, file, cb) => {
      return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
 }
});
const whitePaperFilter = (req, file, cb) => {
 if (file.mimetype === 'application/pdf') {
      cb(null, true)
 } else {
      cb(null, false)
 }
};
const whitePaperUpload = multer({
 storage: whitePaperLink,
 limits: {
      fileSize: 1024 * 1024 * 5
 },
 fileFilter: whitePaperFilter
 });

router.post('/', checkAuth, imageUpload.single('imgURL'), whitePaperUpload.single('whitePaperLink'), 
PostController.create_Post)
控制器文件

exports.create_Post = async (req, res) => {
 const post = new Post({
      title: req.body.title,
      category: req.body.category,
      description: req.body.description,
      imgURL: req.file.path,
      whitePaperLink: req.file.path,
      publishDate: req.body.publishDate,
 });

 try {
      const addPost = await post.save()
      res.status(201).json({
           message: 'Post Added Succesfully.'
      })
 } catch (error) {
      console.log(error);
      res.status(500).json({
           message: error
      })

 }
}

如果对每个字段使用
upload.single
,则会给出错误
意外字段

Multer一次获取所有文件以供执行,在您的情况下,您有两个不同的文件,它会将两个文件都上载到
上。single

因此,不要使用
upload.single
而使用
upload.fields

在您的
route.js
中,按如下方式操作:

const destination = (req, file, cb) => {
     switch (file.mimetype) {
          case 'image/jpeg':
               cb(null, './images/');
               break;
          case 'image/png':
               cb(null, './images/');
               break;
          case 'application/pdf':
               cb(null, './whitePaper/');
               break;
          default:
               cb('invalid file');
               break;
     }
}

const storage = multer.diskStorage({
     destination: destination,
     filename: (req, file, cb) => {
          return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
     }
});

const fileFilter = (req, file, cb) => {
     if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'application/pdf') {
          cb(null, true)
     } else {
          cb(null, false)
     }
};

const upload = multer({
     storage: storage,
     limits: {
          fileSize: 1024 * 1024 * 5,
     },
     fileFilter: fileFilter
});

// add post
router.post('/', upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }]), PostController.create_Post)
const uploadPostData = (req, res, next) => {
     upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }])(req, res, (err) => {
          console.log(req.files);
          req.body.imgURL = req.files.imgURL[0].path.replace('/\\/g','/');
          req.body.whitePaperLink = req.files.whitePaperLink[0].path.replace('/\\/g','/');
          next()
     })
}

// add post
router.post('/', uploadPostData, PostController.create_Post)

编辑:

您也可以这样做:

const destination = (req, file, cb) => {
     switch (file.mimetype) {
          case 'image/jpeg':
               cb(null, './images/');
               break;
          case 'image/png':
               cb(null, './images/');
               break;
          case 'application/pdf':
               cb(null, './whitePaper/');
               break;
          default:
               cb('invalid file');
               break;
     }
}

const storage = multer.diskStorage({
     destination: destination,
     filename: (req, file, cb) => {
          return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`);
     }
});

const fileFilter = (req, file, cb) => {
     if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' || file.mimetype === 'application/pdf') {
          cb(null, true)
     } else {
          cb(null, false)
     }
};

const upload = multer({
     storage: storage,
     limits: {
          fileSize: 1024 * 1024 * 5,
     },
     fileFilter: fileFilter
});

// add post
router.post('/', upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }]), PostController.create_Post)
const uploadPostData = (req, res, next) => {
     upload.fields([{ name: 'imgURL', maxCount: 1 }, { name: 'whitePaperLink', maxCount: 1 }])(req, res, (err) => {
          console.log(req.files);
          req.body.imgURL = req.files.imgURL[0].path.replace('/\\/g','/');
          req.body.whitePaperLink = req.files.whitePaperLink[0].path.replace('/\\/g','/');
          next()
     })
}

// add post
router.post('/', uploadPostData, PostController.create_Post)


您已共享代码,但请说明您面临的错误。@Abhishek I have error is Unexpected field for whitePaperLinkSir我已尝试此操作,但控制器给出的错误未经处理PromisejectionWarning:TypeError:无法读取这两行的未定义属性'path',imgURL:req.file.path,whitePaperLink:req.file.path,图像和pdf保存到文件夹而不是数据库,但它给出了路径错误您是否签入了
req.files
?先生,当我检查req.files时,控制台给出以下结果[Object:null prototype]{imgURL:[{fieldname:'imgURL'}]}[Object:null prototype]{imgURL:[{fieldname:'imgURL'}],whitePaperLink:[{fieldname:'whitePaperLink'}]}当我检查文件时,控制台给出以下结果{fieldname:'imgURL',原始名称:'youtube.png',编码:'7bit',mimetype:'image/png'}{fieldname:'whitePaperLink',originalname:'reactask.pdf',encoding:'7bit',mimetype:'application/pdf'}我已更新了答案。您可以检查我是否已尝试此更新的代码,但它给出的错误是req.files.imgURL[0].path.replaceAll不是函数,我尝试用replaceAll替换replace函数,但它给出的错误与未处理的PromisejectionWarning:TypeError:无法读取未定义的属性“path”