简体   繁体   English

上传图片和 PDF 在 rest API 使用节点 js 与 Z758D31F351CE11CBBF207C522FC516

[英]Upload Image and PDF in rest API using node js with mongoose

I have try to insert some data into mongodb database using node js REST API but I got an error Unexpected field Im new to node please help me.我尝试使用节点 js REST API 将一些数据插入 mongodb 数据库,但我收到一个错误Unexpected field Im new to node please help me。 whitePaper is my pdf file If I upload data like title, description and image only it gives the Correct answer with status code 201 but I try to upload all data and pdf but it gives the error白皮书是我的pdf文件如果我上传标题、描述和图像数据,它只给出状态代码 201 的正确答案,但我尝试上传所有数据和 pdf 但它给出了错误

model code: model 代码:

    description: {
      type: String,
      required: true
    },
    imgURL: {
      type: String,
      required: true
   },
   whitePaperLink: {
      type: String,
      required: true,
                
   },

app.js file app.js 文件

app.use('/whitePaper', express.static('whitePaper'));

router file路由器文件

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)

controller file controller 文件

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
      })

 }
}

If you'll use upload.single for each field it'll give error Unexpected Field .如果您将upload.single用于每个字段,则会给出错误Unexpected Field

Multer takes all files at once for execution, and in your case you've 2 different files and it'll take both files to upload.single . Multer 一次执行所有文件,在您的情况下,您有 2 个不同的文件,它将把两个文件都带到upload.single

So, instead of upload.single use upload.fields .所以,而不是upload.single使用upload.fields

In your route.js , do it like this:在你的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)

Edit:编辑:

You can also do it like this:你也可以这样做:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM