We’re gonna make a Node.js application like this:
Click on Submit button, the file will be uploaded to MySQL database:
We also store the uploaded image in upload folders before saving its data to MySQL.
Then to check MySQL image data, we save the result data in tmp folder.
Project Structure
Let’s look at our project directory tree:
– db.config.js exports configuring parameters for MySQL connection & Sequelize.
– models/index.js: uses configuration above to initialize Sequelize, models/image.model.js for Sequelize model Image.
– views/index.html: contains HTML form for user to upload images.
– routes/web.js: defines routes for endpoints that is called from views, use controllers to handle requests.
– controllers:
home.js returns views/index.html
upload.js handles upload & store images with middleware function.
Open command prompt, change current directory to the root folder of our project.
Install Express, Multer, Sequelize, Mysql2 with the following command:
This Sequelize Model represents images table in MySQL database. These columns will be generated automatically: id, type, name, data, createdAt, updatedAt.
The data field has BLOB type. A BLOB is binary large object that can hold a variable amount of data.
Create middleware for uploading & storing image
Inside middleware folder, create upload.js file with the following code:
In the code above, we’ve done these steps:
– First, we import multer module.
– Next, we configure multer to use Disk Storage engine.
– We also define a filter to only allow images to pass.
You can see that we have two options here:
– destination determines folder to store the uploaded files.
– filename determines the name of the file inside the destination folder.
– We add the [timestamp]-bezkoder- prefix to the file’s original name to make sure that the duplicates never occur.
Now look at the uploadFiles function:
– First we get and check file upload from req.file.
– Next we use Sequelize model create() method to save an Image object (type, name, data) to MySQL database.
data is gotten from uploads folder (that middleware function stored the image).
– If the process is successful, we save write the image data to tmp folder.
– To read/write data, we use fs.readFileSync('/path/to/file') and fs.writeFileSync('/path/to/file', image.data) functions of Node.js fs module.
Create Controller for the view
controllers/home.js
const path = require("path");
const home = (req, res) => {
return res.sendFile(path.join(`${__dirname}/../views/index.html`));
};
module.exports = {
getHome: home
};
Create View for uploading image
In views folder, create index.html file with the HTML and Javascript code as below:
There are 2 routes:
– GET: Home page for the upload form.
– POST "/upload" to call the upload controller. This is for action="/upload" in the view.
The single() function with the parameter is the name of input tag (in html view: <input type="file" name="file">) will store the single file in req.file.