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

时间:2019-01-30 11:38:54

标签: node.js mongodb multer

当用户提交表单并将其插入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();
});

我刚刚上传了所需的代码。我收到无法读取未定义的属性'userPhoto'的错误。我不知道我应该在fs.readFilesync中写什么。请帮助我将图像插入服务器。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您要求Multer处理一个.single()文件,该文件应由输入名称"files"引用。根据{{​​3}}:

  

单个文件将存储在req.file

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

另请参阅doc,Multer公开了检索上载文件的路径。

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

编辑:一些评论

// 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
  • 如果Multer在请求上安装了req.file,它将公开多个数据字段,例如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) => {...});

这样,所有其他路由都不会考虑文件上传,我敢肯定我不需要强调这有多好。