To upload an image file in Node Express js using Multer & MySQL; Simply install the multer and MySQL modules in the Node Express app using command npm install express multer body-parser mysql
, and use Multer to save the image file in the project folder and MySQL INSERT INTO table_name(file_src)VALUES(?)
query to store the image file name.
Multer module is middleware, which is used to handle multipart/form-data in Node JS to upload files.
Upload/Store Image File in MySQL using Node. js, Express & Multer
Steps to upload/save image file in MySQL database using Node express js and multer:
Step 1 – Create Node Express js App
Start cmd or terminal window and run the following commands into it to create node express js application:
mkdir my-app cd my-app npm init -y mkdir uploads
Step 2 – Create Table in MySQL Database
To create a table in MySQL database; simply run the following SQL query for:
CREATE TABLE users_file(id INT(10) NOT NULL AUTO_INCREMENT, file_src TEXT, PRIMARY KEY(id));
Step 3 – Install express multer body-parser mysql Modules
To install express, multer, bodyparser and mysql
modules in the node express js application, which will help to upload image files into MySQL database and application folder, Simply run the npm install express multer body-parser mysql
command on cmd or terminal window:
npm install express multer body-parser mysql
Step 4 – Create Image File Upload Form
To create image file upload form in a node express js application or project; Simply navigate to the root directory of project and create index.html
file and then add the following code into it:
<!DOCTYPE html> <html lang="en"> <head> <title>How to store image path in MySQL database using Node js - Tutsmake.com</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>How to store image path in MySQL database using Node js - Tutsmake.com</h1> <form action="/uploading" enctype="multipart/form-data" method="post"> <input type="file" name="image" accept='image/*' > <input type="submit" value="Upload"> </form> </body> </html>
Note that:- A form with a `file input` element that allows us to choose the file and a button to submit the form.
Step 5 – Create Server.js File and Import Modules & Routes
Navigate to your project root directory and create server.js file, Then import express multer body-parser mysql modules in server.js; like the following:
const express = require('express') const app = express() const bodyparser = require('body-parser') const mysql = require('mysql') const multer = require('multer') const path = require('path') // body-parser middleware use app.use(bodyparser.json()) app.use(bodyparser.urlencoded({ extended: true })) // Database connection const db = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "test" }) db.connect(function (err) { if (err) { return console.error('error: ' + err.message); } console.log('Connected to the MySQL server.'); }) //! Use of Multer var storage = multer.diskStorage({ destination: (req, file, callBack) => { callBack(null, './uploads/') // './uploads/' directory name where save the file }, filename: (req, file, callBack) => { callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)) } }) var upload = multer({ storage: storage }); //create connection const PORT = process.env.PORT || 3000 app.listen(PORT, () => console.log(`Server is running at port ${PORT}`))
Import Routes for Upload and Store Image File in MySQL DB using Multer
Simply import the following routes in server.js
for showing the image file upload form and store image file in mysql db & folder route using multer:
//! Routes start //route for Home page app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); //@type POST //route for post data app.post("/uploading", upload.single('image'), (req, res) => { if (!req.file) { console.log("No file upload"); } else { console.log(req.file.filename) var imgsrc = 'http://127.0.0.1:3000/uploads/' + req.file.filename var insertData = "INSERT INTO users_file(file_src)VALUES(?)" db.query(insertData, [imgsrc], (err, result) => { if (err) throw err console.log("file uploaded") res.send('Image Has been uploaded, please check your directory and mysql database....'); }) } });
Step 6 – Start App Server
Run the npm start
to start uploading image file in MySQL database using node js express app server:
//run the below command npm start after run this command open your browser and hit http://127.0.0.1:3000/
Conclusion
That’s it; You have learned how to upload and store image path in MySQL database using Node js express using multer module.