Search code examples
mysqlsqlnode.jsexpress

error column cannot be null, trying to upload file into sql


i am still new in node js, and i am trying to make some backend with file upload/ image upload function that can be stored in sql, i am trying using multer but it cant read my file while testing in postman body. anybody can help me where i do wrong? here is my controller

const { db } = require('./db');
const bodyParser = require('body-parser');


const getgambar = (req, res) => {
const sqlQuery = "SELECT * FROM gambar";

  db.query(sqlQuery, (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
      console.log(result);
    }
  });
};

const addgambar = (req,res) => {
    
    const idimg = req.body.idimg;
    const gambar = req.file.gambar;

    console.log()
    
    const sqlQuery = "INSERT INTO image (idimg,gambar) VALUE (?,?)";
    
    db.query(sqlQuery, [idimg,gambar], (err, result) => {
      if (err) {
        res.send({
            message: "error",
            err
        })
      } else {
        res.send({
            message: "YES"
        })
      }
    });

};
module.exports = {
    getgambar,
    addgambar,
};

here is my route

const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const ctrl = require('./gambarctrl');

const storange = multer.diskStorage({
    destination: './uploads',
    filename: (req, file, cb) => {
        return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
    }
})

const upload = multer({
    storange: storange
})

router.get('/image/display', ctrl.getgambar)
router.post('/image',upload.single('gambar'), ctrl.addgambar)

module.exports = router;

and here my index

const { db } = require('./db');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express();
const fileUpload = require('express-fileupload');
const gambarroute = require ('./gambarroute');
const multer = require('multer');



app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(gambarroute);

app.listen(3000, () => {
    console.log('on port 3000!');
  });

i am still quite new in node js and i am still searching for tutorial, i appriciate for the help.


Solution

  • Two problems here...

    1. Multer puts the single uploaded file into req.file so you should use

      const gambar = req.file; // no `.gambar`
      
    2. Assuming your DB column is a BLOB or BINARY type, you need to provide a Buffer.

      Since you're storing the images within the DB, you don't need to use DiskStorage. Use MemoryStorage instead which provides a Buffer out-of-the-box

    const upload = multer({
      storage: multer.memoryStorage(), // watch your spelling
    })
    

    Then bind the .buffer property in your query.

    db.query(sqlQuery, [idimg, gambar.buffer], (err, result) => {
      // ...
    });
    

    To respond with the image from Express, use something like this

    router.get("/image/display/:id", (req, res, next) => {
      db.query(
        "SELECT `gambar` FROM `image` WHERE `idimg` = ?",
        [req.params.id],
        (err, results) => {
          if (err) {
            return next(err);
          }
    
          if (!results.length) {
            return res.sendStatus(404);
          }
    
          // set the appropriate content type
          res.set("Content-Type", "image/jpg");
          res.send(results[0].gambar);
        }
      );
    });
    

    and from the frontend...

    <img src="http://localhost:3000/image/display/some-id" />