I am having a problem loading a Multer image on the server, the file loads to the path but not to the database

Asked

Viewed 39 times

0

On my machine works perfectly, the image is loaded to the path and all data to the database but on the Ubuntu server with the same code and the same database only the image is loaded to the path and none of the data is loaded to the db.

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/imgcomment/'),
      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);
  }
  }).single('images');


// 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 nome = req.body.nome;
    const descricao = req.body.descricao;
    const preco = req.body.preco;
    const category = req.body.category;

      if(err){

        console.log(err)

      } else {

        if(req.file == undefined){

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

        } else {

          values.push([nome, descricao, preco, file_name, category]);
          console.log(values)

          db.query('INSERT INTO produtos (nome, descricao, preco, images, categoria) VALUES ?', [values], function (err, result) {
            if (err) {
              error = 'SQL ERROR ' + err.sqlMessage;
            }
            else {
              error = 'Blog added successfully';
            }
            req.flash('success', error);
            res.redirect('/todolist');
          });
          
        }
      }
    })
}

module.exports = {
    uploadImg: uploadImg
}

Does anyone know what might cause this problem? thank you very much

1 answer

0

It is probably because you need the data and the file at the same time and in the server Parsing may take a while. Try using any method instead of single in multer.

Browser other questions tagged

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