无法使用 NodeJS 将图像插入 MongoDB 服务器

Failed to insert image into MongoDB server using NodeJS

我正在尝试在用户提交表单并将其插入 mongoDB 时获取图像 server.For 我正在使用 Multer 插件,但它向我显示 error.Here 是我的代码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 属性 'userPhoto' of undefined 的错误。我不知道我应该在 fs.readFilesync.Please 中写什么帮助我插入图像到服务器。

问题不在于猫鼬!正如您的错误消息中所说,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();
});

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

The single file will be stored in req.file

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

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

最后,您可能希望将 middleware usage 限制在需要它的路线上。

编辑:一些评论

// 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,而只是为需要它的路由启用。除了 "global" app.use,您还可以定义多次路由(或者您可以显式使用路由器,我看不出有什么区别),例如:

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

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

date: { type: Date, default: Date.now } // stick that into the Schema