使用Nodejs将包含图像的对象上传到Mongodb?

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

我想使用nodejs将包含图像的对象上传到mongodb数据库,但我无法这样做。

角度文件

onSelectedFile(event){
this.edit_image = event.target.files[0];   
}


editProfile(e){ 
const user={
  email:this.edit_email,
  img:this.edit_image,
}
console.log("To Update");
console.log(user);
this._authService.editProfile(user)
      .subscribe(data=>{
        this.dataFromService=data;
        this.user=this.dataFromService.user;
        console.log(data);
      })
}

在服务文件中

editProfile(user){
let headers = new HttpHeaders();

headers=headers.append('content-type','application/json');
console.log("Updating Profile");
console.log(user);
return this.http.post('http://localhost:8080/profile/edit_Profile',user,{headers:headers})
        .pipe(catchError(this.errorHandler))
  }

在Nodejs文件中

router.post('/edit_profile', (req, res) => {
let updateProfile = {
    email: req.body.email,
    img: req.body.img
};

console.log("Profile");
console.log(updateProfile); //to check the data
console.log("Profile");

Profile.updateP(updateProfile, (err, user) => {
    if (err) throw err;
    else {
        console.log("Update User");
        console.log(user);
        res.json({
            user: user
        })
    }
})
})

在profileUpdate中记录数据时,它会打印img的空值

用户架构

const profileSchema = schema({
email: {
    type: String,
},
img: { data: Buffer, contentType: String }
});

我想更新现有的配置文件,但我无法使用multer甚至将图像数据从angular文件传递到nodejs文件

node.js angular mongodb express mean-stack
2个回答
0
投票

您可以将图像转换为base64格式,这非常容易处理并存储在数据库函数中以将图像转换为base64: -

var fs = require('fs');

function base64_encode(){
    var imageAsBase64 = fs.readFileSync('test.png', 'base64');
    // code to store it in the mongodb here
}

将base64转换为图像的功能: -

    var fs = require('fs');

    function base64_decode(){
        var imageAsBase64 //some base64 encoded string
        var data = imageAsBase64..replace(/^data:image\/png;base64,/, "")
        fs.writeFile("out.png", data, 'base64', function(err) {
            console.log(err);
         });

    }

0
投票

而不是将图像上传到数据库使用类似s3的东西来存储图像并将链接上传到mongodb上的图像

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