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

Uploading an object containing image to Mongodb using Nodejs?

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

Angular 文件

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 文件

与其将图像上传到数据库,不如使用 s3 之类的东西来存储图像并将 link 上传到 mongodb

上的该图像

您可以将您的图像转换成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);
         });

    }