【问题标题】:Failed to insert image into MongoDB server using NodeJS无法使用 NodeJS 将图像插入 MongoDB 服务器
【发布时间】:2022-02-18 06:24:43
【问题描述】:

当用户提交表单并将其插入 mongoDB 服务器时,我正在尝试获取图像。对于图像,我正在使用 Multer 插件,但它向我显示错误。这是我的 NodeJS 代码

const multer = require('multer');
mongoose.connect('mongodb://localhost:27017/mytable',{useNewUrlParser:true} )
.then(()=>
console.log("Mongodb connected"))
.catch(err => console.error("could not connected",err));
const Schema =new mongoose.Schema({
    name:String,
    email:String,
    lastname:String,
    pass:String,
    phonenumber:String,
    zipcode:String,
    birthdate:String,
    img:  {contentType:String,data:Buffer }

});
Schema.plugin(mongoosePaginate)
var user = mongoose.model('mytable', Schema);
//Multer for include image into directory
app.use(multer({ dest: '/public/'}).single('files'));
app.post('/save',(req,res)=>{

    console.log("image is" +req.body.img);
    var model = new user();
       model.name = req.body.name,
        model.email=req.body.email,
        model.lastname=req.body.lastname,
        model.pass=req.body.pass,
        model.phonenumber=req.body.phonenumber,
        model.zipcode=req.body.zipcode,
        model.birthdate=req.body.birthdate,
     /*   model.img.data = req.body.img,  */
        model.img.data = fs.readFileSync(req.files.userPhoto.path);
        newPic.image.contentType = 'image/png';
        model.save(function(err,doc){

    });
    res.json({result:'sucess'}); 
    res.end();
});

我刚刚上传了所需的代码。我收到 Cannot read property 'userPhoto' of undefined 的错误。我不知道我应该在 fs.readFilesync 中写什么。请帮我将图像插入服务器。

【问题讨论】:

    标签: node.js mongodb multer


    【解决方案1】:

    您要求 Multer 处理一个 .single() 文件,该文件预计将由输入名称 "files" 引用。根据doc

    单个文件将存储在req.file

    但您尝试访问 req.files。 (您似乎希望这个文件被称为"userPhoto",也许吧?)。

    另见what information Multer 公开检索上传文件的路径。

    最后,您可能希望将您的 middleware usage 限制为需要它的路由。

    编辑:一些 cmets

    // This tells the WHOLE app that:
    // when a request comes in, execute this
    app.use(
      // Multer will do:
      // when I'm given an incoming request (here it's every request)
      // then I'm looking for *one* file being uploaded
      // this file should be named "files" (i.e. client has <input type="file" name="files">)
      // if I find it, then I store it in /public
      multer({ dest: '/public/'}).single('files')
    );
    
    // This tells the app that:
    // if a request comes in for endpoint /save with method POST, this is the code to execute
    app.post('/save', (req, res) => {
      // in here, Multer will have been executed already
    });
    

    所以:

    • 您的表单是否真的将要上传的文件命名为"files"?我猜你的表单将文件命名为"userPhoto"...只是猜测!
    • 如果请求中存在这样的文件,Multer 文档说您的路由处理程序可以在 req.file(而不是 req.files)中访问它
    • 如果没有,Multer 只会让请求通过(这就是中间件所做的),所以你不会有 req.file
    • 如果 req.file 被 Multer 挂载在请求上,它会暴露几个数据字段,例如 req.file.path

    我还暗示您可能不想为整个应用启用 Multer,而只是为需要它的路线启用。您可以定义多次路由而不是“全局”app.use(或者您可以显式使用路由器,我看不出有什么区别),例如:

    app.post('/save', multer(...));
    app.post('/save', (req, res) => {...});
    // which can also be written as
    app.post('/save', multer(...), (req, res) => {...});
    

    这样一来,其他所有的路由都不考虑文件上传,我相信我不需要强调这有多好。

    【讨论】:

    • 嗨,我对此完全陌生。你能编辑我的代码吗。我不知道在 multer 中写什么。我尝试了 5-6 种不同的逻辑,但它不起作用。实际上图像来自html表单。
    • 我链接的文档将帮助您不要保持“对此完全陌生”。 ;) 我将在您的代码中使用一些 cmets 进行编辑,以帮助您了解会发生什么,但我无法做到这一切,因为我缺乏一些数据来做到这一点。
    【解决方案2】:

    问题不在于猫鼬!正如您的错误消息中所说,req.files 未定义。 multer 文档有问题!当您使用单个文件时,您的文件将在req.file 中可用 所以这可以解决你的问题:

    app.post('/save',(req,res)=>{
    
        console.log("image is" +req.body.img);
        var model = new user();
           model.name = req.body.name,
            model.email=req.body.email,
            model.lastname=req.body.lastname,
            model.pass=req.body.pass,
            model.phonenumber=req.body.phonenumber,
            model.zipcode=req.body.zipcode,
            model.birthdate=req.body.birthdate,
         /*   model.img.data = req.body.img,  */
            model.img.data = fs.readFileSync(req.file.path); // here's the fix
            newPic.image.contentType = 'image/png';
            model.save(function(err,doc){
    
        });
        res.json({result:'sucess'}); 
        res.end();
    });
    

    【讨论】:

    • 您好,谢谢您的回答。在实施您的结果后。我收到此错误:无法读取未定义的属性“路径”
    【解决方案3】:
    date: { type: Date, default: Date.now } // stick that into the Schema
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2020-05-07
      • 2017-07-31
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      相关资源
      最近更新 更多