Search code examples
mysqlnode.jsmultipartform-datamulterform-data

How to post form data ( image and data ) using MULTER, Nodejs and MySQL


I want to upload an image with a data on my form data using NodeJS, Multer and MySQL.

As you can see below, my code :

Table MySQL :

CREATE TABLE produits (
 Codep bigint(21) NOT NULL AUTO_INCREMENT,
 Description varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 Img varchar(255) NOT NULL,
 PRIMARY KEY (Codep )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10;

My router :

const path = require('path');
const multer = require('multer');
const crypto = require('crypto');
const fs = require('fs');
var imge = "";
var storage = multer.diskStorage({
  destination: function (req, file, cb){
    cb(null, '../public/uploads')
  },
  filename: function (req, file, cb){
    crypto.pseudoRandomBytes(32, function(err, raw){
        imge = raw.toString('hex') + path.extname(file.originalname);
        cb(null, imge);
    })
  }
});

var upload = multer({storage: storage});
exports.ajouterprod = function(req, res) {

    console.log("req", req.body);
    var today = new Date();
    var produits = {
        "Description": req.body.Description,
        "Img":  imge
    }
      upload.single('produits[Img]')
    connection.query('INSERT INTO produits SET ?', produits, function(error, results, fields) {
        if (error) {
            console.log("error ocurred", error);
            res.send({
                "code": 400,
                "failed": "error ocurred"
            })
        }
        else {
            res.send({
                "code": 200,
                "success": "produit registered sucessfully"
            });
        }
    })
};

My server :

router.post('/ajouterprod', produits.ajouterprod);

When I try that with Postman as you see below :

enter image description here

I get :

req {}
error ocurred { Error: ER_BAD_NULL_ERROR: Column 'Description' cannot be null

How can I fix that please ?


Solution

  • Your issue lies in req.body. Because it's returning an empty object, the MySQL framework is trying to set Description to null, which is not valid. Doing a console.log(produits) would reveal they're all null/undefined.

    I would suggest looking through this answer, as you need to use a body-parser that can handle file uploads.

    Additionally, it seems you're using multer wrong:

    var upload = multer({storage: storage}).single('Img');
    exports.ajouterprod = function(req, res) {
        upload(req, res, function(imageUploadErr) {
            console.log("req", req.body);
            var today = new Date();
            var produits = {
                "Description": req.body.Description,
                "Img":  imge // (Wrong variable name, I think you want req.body.Img)
            }
    
            connection.query('INSERT INTO produits SET ?', produits, function(error, results, fields) {
                if (error) {
                    console.log("error ocurred", error);
                    res.send({
                        "code": 400,
                        "failed": "error ocurred"
                    })
                }
                else {
                    res.send({
                        "code": 200,
                        "success": "produit registered sucessfully"
                    });
                }
            })
        });
    };