想要在mongodb中上传带有表单的图像

问题描述 投票:0回答:1

mongodb atlas 上有一个名为 food_items 的数据库文件,我想从前端表单上传图像和数据

错误:多部分:未找到边界 在新的多部分(D:com2 - 复制 ode_modules usboy\lib ypes\multipart.js:233:13) 在 getInstance (D: com2 - 复制 ode_modules usboy\lib\index.js:33:12)

`const multer = require('multer');
const path = require('path');
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './upload/');
  },
  filename: (req, file, cb) => {
    // specify the filename for the uploaded files
    cb(null, Date.now() + path.extname(file.originalname));
  },
});
const upload = multer({ storage: storage });
router.post('/addmenu', upload.single('image'), async(req, res) => {
    try{
      const image = req.file;
        const food_items = new global.food_items({
            CategoryName: req.body.catname,
            name: req.body.name,
            img: image.path,
            options: [{
              medium: req.body.price1,
              large: req.body.price2,
            }],
            description: req.body.description
        });
        await food_items.save();
            res.status(201).send({ message: 'Food item created successfully' });
          } catch (error) {
            console.error(error);
            res.status(500).send({ message: 'Internal server error' });}
});

module.exports = router;`
`   const submitImage = async (e) => {
        e.preventDefault();
        const formData = new FormData();
    
        formData.append('catname', catname);
        formData.append('name', name);
        formData.append('image', image);
        formData.append('price1', price1);
        formData.append('price2', price2);
        formData.append('description', description);
                    
        fetch("http://localhost:4000/api/addmenu", {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data'
              },
            body: formData,
        })
            .then((response) => response.json())
            .then((data) => {
                console.log(data);
            }).catch((error) => {
                console.error(error);
            });
    };`
`const mongoose = require('mongoose');
const pass = 'mongodb+srv://Admin:[email protected]/mern_website_burger_bro';
const connectToMongo = async () => {
  try {
    mongoose.set('strictQuery', false);
    await mongoose.connect(pass);
    console.log('Connected to MongoDB successfully!');
    const foodSchema = new mongoose.Schema({
      CategoryName: String,
      name: String,
      img: String,
      options: [{
        medium: String,
        large: String,
      }],
      description: String
    });
    
    const categorySchema = new mongoose.Schema({
      CategoryName: String,
    });
    const Food = mongoose.model('food_items', foodSchema);
    const Category = mongoose.model('food_categories', categorySchema);
    
    try {
      const foodItems = await Food.find({});
      global.food_items = foodItems;
      // console.log(global.food_items);
    } catch (foodError) {
      console.log('Error fetching food items:', foodError);
    }
    try {
      const categories = await Category.find({});
      global.food_category = categories;
      // console.log(global.food_category);
    } catch (categoryError) {
      console.log('Error fetching food categories:', categoryError);
    }
  } catch (error) {
    console.log('MongoDB connection error:', error);
  }
};

module.exports = connectToMongo;`
node.js reactjs mongodb mongoose multer
1个回答
0
投票

给您一些可能对您有帮助的信息

  1. 请分享技术栈 例如,如果您提供您所使用的节点、框架等版本信息,就很容易识别该版本的问题。

(软件包等往往是在社区中制作和分发的,这并不能保证企业级的完整性。)

  1. 解决你的问题 通过使用 Stackblitz 的类似在线工具解决问题来获取建议 通过复制与您的项目类似的环境进行测试对于解决问题有很大帮助。

您提供的错误有多种因素,但总结起来,有以下几点。

busboy 库是 Node.js 中广泛使用的库,用于处理文件上传和多部分表单数据。当 HTTP 请求的 Content-Type 标头不包含或指定不正确时,通常会出现“未找到边界”错误。

如果您分享调试后的结果,社区可以推断出更多问题的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.