简体   繁体   中英

Upload Image to MySQL with nodejs and multer

Hello all: I am working on this node, express, mysql program that needs to upload an image and store its name in MySQL. The image gets uploaded just fine, but I cannot do the insert into MySQL. Sometimes I do not get an error, but the file name is not inserted into the database. Other times, I get the error that filename is undefined.

Here is my index.html:

<body>
    This is the webpage
    <p></p>
    <!-- make sure to put enctype="multipart/form-data" -->
    <form id="upload" enctype="multipart/form-data" action="/upload" method="POST" class="upload-form">
        <label>Select file</label><br />
        <input type="file" name="upload" />
        <br />
        <p></p>
        <button type="submit">Submit</button>
    </form>
 </body>

This is my server.js:

//setting up an express server.

//load express
const express = require('express');
//load multer
const multer = require('multer');
const app = express();
const path = require('path');
// const fs = require('fs');


//mysql stuff
mysql = require('mysql')
bodyParser = require("body-parser");
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'pass123!',
  database : 'images_db'
});

connection.connect();
 
global.db = connection;

//endf of mysql stuff
const PORT = process.env.PORT || 3001;
app.use(express.static(path.join(__dirname, "public")));

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'images/')
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
    // cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  },  
});

const limits = {
    fileSize : 4000000
}

//fileFilter function controls which files should be uploaded. req = request being made. file = contains file info. cb = callback function to tell multer when we are done filtering the file. send back an error message to the client with cb.
const fileFilter =(req, file, cb) => {
  //if the file is not a jpg, jpeg, or png file, do not upload it multer; reject it.
  if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
      return cb(new Error('File must be of type JPG, JPEG, or PNG and nore more than 2MB in size'))
  }
  //undefined = nothing went wrong; true = that is true, nothing went wrong, accept the upload.
  cb(undefined, true)
}

//set up the multer middleware
const upload = multer({
    storage: storage,
    limits: limits,
    fileFilter: fileFilter
    // filename: filename
  })

// ROUTES
app.get('/',function(req,res){
    res.sendFile(__dirname + '/index.html');
  });

  //app.use('/image', express.static('./upload')); // shared uploaded folder with users so users can access the profile images though image folder path


//upload image post route: localhost:port/upload
  app.post("/upload",upload.single('upload'), (req, res) => {
 

    // res.send();
    //mysql stuff
    // var sql = "INSERT INTO `file`(`name`, `type`, `size`) VALUES ('" + req.file.filename + "', '"+req.file.mimetype+"', '"+req.file.size+"')";
    var sql = "INSERT INTO `file`(`name`) VALUES ('" + req.file.filename + "')";
 
    var query = db.query(sql, function(err, result) {
       console.log('inserted data');
    });
    message = "Successfully! uploaded";
    //res.render('index',{message: message, status:'success'});
    //end of mysql stuff
     
    res.redirect('./');
   
}), (error, req, res, next) => {
    res.status(400).res.send("You have successfully uploaded the file!");
    // res.redirect('/');
}



app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}!`);
})

I got the solution by replacing this code:

var sql = "INSERT INTO `file`(`name`) VALUES ('" + req.file.filename + "')";
 
    var query = db.query(sql, function(err, result) {
       console.log('inserted data');
    });

with this code (parameterized query):

    let sql = "INSERT INTO  image (name) VALUES (?)";

   db.query(sql, [req.file.filename], function(err, result) {
       console.log('inserted 88 data');
      //  console.log("query ", sql2);
    });

Now, I can both upload an image to the server and insert the name of that image into a MySQL database. I hope this helps anyone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM