Search code examples
node.jsmongodbexpressmongoosemultipartform-data

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


TypeError [ERR_INVALID_ARG_TYPE]: The "size" argument must be of type number. Received type string ('/9j/4AAQSkZJRgABAgEBLAEs...) While Executing..

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,

Followed retrieving image procedure from: https://codebun.com/upload-image-in-database-using-nodejs-and-mongodb/

Please help.


Solution

  • Buffer.alloc() creates a new buffer object of the specified size, and you are sending the string. Use Buffer.from() instead.

    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 
        }