/////////////////////////////////////////////////// js file


const expressPk = require('express');
const fsPk = require('fs');
const appPk = expressPk();
const mysqlPk = require('mysql');
const bodyParserPk = require('body-parser');
const multerPk = require('multer');
const pathPk = require('path');

// Set up MySQL connection
const dbPk = mysqlPk.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root@123',
  database: 'abc',
});

dbPk.connect((err) => {
  if (err) {
    throw err;
  }
  console.log('Connected to MySQL database');
});

// Configure multer for file uploads
const storagePk = multerPk.diskStorage({
  destination: './public/uploads/',
  filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + pathPk.extname(file.originalname));
  },
});

const uploadPk = multerPk({ storage: storagePk });

// Configure EJS as the template engine
appPk.set('view engine', 'ejs');
appPk.use(expressPk.static('public'));

// Parse incoming requests
appPk.use(bodyParserPk.urlencoded({ extended: false }));
appPk.use(bodyParserPk.json());

// Routes
appPk.get('/', (req, res) => {
  res.render('demo');
});

appPk.post('/upload', uploadPk.single('image'), (req, res) => {

 try {

   const { filename, path } = req.file;

   const { type } = req.body;

   console.log(type);

   // Read the uploaded file

   const image = fsPk.readFileSync(path);

   // Convert the image to Base64 string

   const encodedImage = image.toString('base64');

   const sql = 'INSERT INTO product (pname, pimage, type) VALUES (?, ?, ?)';

   dbPk.query(sql, [filename, Buffer.from(encodedImage, 'base64'), type], (err, result) => {

     if (err) {

       console.error('Failed to execute the database query:', err);

       res.status(500).send('Failed to upload image.');

       return;

     }

     res.send('Image uploaded successfully.');

   });

 } catch (err) {

   console.error('An error occurred during image upload:', err);

   res.status(500).send('Failed to upload image.');

 } finally {

   // Delete the temporary file

   // if (path) {

   //   fs.unlink(path, (err) => {

   //     if (err) {

   //       console.error('Failed to delete the temporary file:', err);

   //     }

   //   });

   // }

 }
});

// Start the server
const portPk = 3008; // Or any other port you prefer

appPk.listen(portPk, () => {
 console.log(`Server started on port ${portPk}`);
});


//////////////////////////////////////////////   ejs file ////////////////////////


<!DOCTYPE html>
<html>
<head>
   <title>Image Upload</title>
</head>
<body>
   <h1>Image Upload</h1>
   <form id="uploadFormPk" enctype="multipart/form-data">
       <input type="file" name="imagePk" id="imageInputPk" />
       <input type="submit" value="Upload" id="uploadBtnPk" />
   </form>
   <div id="messagePk"></div>
   <div id="imageContainerPk"></div>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script>
       $(document).ready(function () {
           $('#uploadFormPk').submit(function (event) {
               event.preventDefault();
               var formDataPk = new FormData(this);
               $.ajax({
                   url: '/upload',
                   type: 'POST',
                   data: formDataPk,
                   processData: false,
                   contentType: false,
                   success: function (responsePk) {
                       $('#messagePk').html(responsePk);
                       $('#imageInputPk').val('');
                       var imgPk = document.createElement('img');
                       imgPk.src = 'data:image/jpeg;base64,' + formDataPk.get('imagePk');
                       $('#imageContainerPk').html(imgPk);
                   },
                   error: function (xhrPk, statusPk, errorPk) {
                       console.log(errorPk);
                   },
               });
           });
       });
   </script>
</body>
</html>