Upload Multifiles with Multer , express , nodejs and query to Mysql

Asked

Viewed 108 times

-2

How to query the name of two different images for mysql?

I’m using a woman to upload more than one image, and the code I used is working perfectly. The images are loaded into my briefcase imgpost. My problem is to query the name of each image for my mysql database.

Here is the code used:

    const path = require('path')
    const multer  = require('multer')

    const uploadImg = function (req, res) {
        
      let file_name = ''
      var values = [];

      const storage = multer.diskStorage({

          destination: path.join(__dirname, '../../public/imgpost/'),
          filename: function(req, file, cb){
            const uni = new Date().getTime();
            file_name = uni + '-' + file.originalname
            cb(null, uni + '-' + file.originalname);
          }

      });



      const upload = multer({
      storage: storage,
      fileFilter: function(req, file, cb){
          checkFileType(file, cb);
      }
      }).any();


    // Check File Type
      function checkFileType(file, cb){

        // Allowed ext
        const filetypes = /jpeg|jpg|png|gif/;
        // Check ext
        const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
        // Check mime
        const mimetype = filetypes.test(file.mimetype);
      
        if(mimetype && extname){
          return cb(null,true);
        } else {
          cb('Error: Images Only!');
        }

      }

      

      upload(req, res, (err) => {

        const titulo = req.body.titulo;
        const firstp = req.body.firstp;
        const categoria = req.body.categoria;
       
        
          if(err){

            console.log(err)

          } else {

            if(req.file == undefined){

              console.log('Error: No File Selected!')

            } else {

              values.push([titulo, firstp,  file_name,  categoria]);
              console.log(values)

              db.query('INSERT INTO posts (titulo, firtsp, first_image,  categoria) VALUES ?', [values], function (err, result) {
                if (err) {
                  error = 'SQL ERROR ' + err.sqlMessage;
                }
                else {
                  error = 'Blog added successfully';
                }
                req.flash('success', error);
                res.redirect('/blogue');
              });
              
            }
          }
        })
    }

    module.exports = {
        uploadImg: uploadImg
    }

With this code, if for example load two images the name(file_name) of the last uploaded image is sent to my table first_image, i would like to know how to send the name of the other image to a second table second_image. Someone who can help?

1 answer

-1

I found out how to do it! Thanks anyway and I leave here the solution for other beginners like me :

const path = require('path')
const multer  = require('multer')

const uploadImg = function (req, res) {
    
  let file_name = ''
  
  var values = [];

  const storage = multer.diskStorage({

      destination: path.join(__dirname, '../../public/imgpost/'),
      filename: function(req, files, cb){
        const uni = new Date().getTime();
        file_name = uni + '-' + files.originalname
        cb(null, uni + '-' + files.originalname);
        
      }
  });


  const upload = multer({
  storage: storage,
  fileFilter: function(req, files, cb){
      checkFileType(files, cb);
  }
  }).fields([{ name: 'first_image', maxCount: 1 }, { name: 'second_image', maxCount: 1 }])


// Check File Type
  function checkFileType(files, cb){

    // Allowed ext
    const filetypes = /jpeg|jpg|png|gif/;
    // Check ext
    const extname = filetypes.test(path.extname(files.originalname).toLowerCase());
    // Check mime
    const mimetype = filetypes.test(files.mimetype);
  
    if(mimetype && extname){
      return cb(null,true);
    } else {
      cb('Error: Images Only!');
    }

  }

  upload(req, res, (err) => {

    const titulo = req.body.titulo;
    const firstp = req.body.firstp;
    const categoria = req.body.categoria;
    const image1 = req.files['first_image'][0].filename;
    let image2 = "";
    if(req.files['second_image']){
    image2 = req.files['second_image'][0].filename;
    }
    
      if(err){

        console.log(err)

      } else {

        if(req.files == undefined){

          console.log('Error: No File Selected!')
        

        } else {

          values.push([titulo, firstp,  image1, image2,  categoria]);
          console.log(values)

          db.query('INSERT INTO posts (titulo, firtsp, first_image, second_image, categoria) VALUES ?', [values], function (err, result) {
            if (err) {
              error = 'SQL ERROR ' + err.sqlMessage;
            }
            else {
              error = 'Blog added successfully';
            }
            req.flash('success', error);
            res.redirect('/blogue');
          });
          
        }
      }
    })
}

module.exports = {
    uploadImg: uploadImg
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.