0

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 ?

Ichrak Mansour
  • 1,850
  • 11
  • 34
  • 61

1 Answers1

1

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"
                });
            }
        })
    });
};
Blue
  • 22,608
  • 7
  • 62
  • 92
  • I used `app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());` but it's still the same issue . – Ichrak Mansour Jul 29 '18 at 14:45
  • 1
    @CodeLover Updated answer – Blue Jul 29 '18 at 14:50
  • Thank you @Franker I get `produit registered sucessfully` , but when I access to `/public/uploads` I don't find the image which I upload it. – Ichrak Mansour Jul 29 '18 at 15:08
  • Try using an absolute value for the directory. My guess is the current directory may not be what you think it is. – Blue Jul 29 '18 at 15:12
  • I used `app.use(express.static('/public/uploads'));` , but I don't find it. – Ichrak Mansour Jul 29 '18 at 15:19
  • 1
    Check `imageUploadError` and see if there is something wrong. Additionally, make sure `/public/uploads` is writeable by node.js. (Make sure it's absolute to the server, not the root directory of the app). – Blue Jul 29 '18 at 15:21
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176971/discussion-between-codelover-and-frankerz). – Ichrak Mansour Jul 29 '18 at 15:33