使用 Node/Expressjs 将图像从表单加载到 MongoDB 时出错

Error while Loading image from form into MongoDB using Node/Expressjs

TypeError [ERR_INVALID_ARG_TYPE]:“大小”参数必须是数字类型。收到类型字符串 ('/9j/4AAQSkZJRgABAgEBLAEs...) 执行时..

app.post('/register',upload.single('img'), (req, res) => {
    var img = fs.readFileSync(req.file.path);
    var encode_img = img.toString('base64');
    var final_dp={
        contentType:req.file.mimetype,
        dp:Buffer.alloc(encode_img,'base64')
    }
    try {
    const password = req.body.fPass; 
    const Spassword = req.body.sPass;// So that form's passwords are same
    if(password == Spassword){
        var obj = {
            dp: final_dp,

从以下位置检索图像程序:https://codebun.com/upload-image-in-database-using-nodejs-and-mongodb/

请帮忙。

Buffer.alloc() 创建指定 大小 的新缓冲区对象,并且您正在发送 字符串 。请改用 Buffer.from()

app.post('/register',upload.single('img'), (req, res) => {
    var img = fs.readFileSync(req.file.path);
    var base64_img = Buffer.from(img).toString('base64');
    var final_dp={
        contentType: req.file.mimetype,
        dp: base64_img 
    }