how to upload images with slate JS

In this tutorial, I will show you how to upload/store image in MySQL database using Node.js with the help of Multer and Express.

Related Posts:
– How to upload multiple files in Node.js
– Upload & resize multiple images in Node.js using Express, Multer, Precipitous
– How to upload/store images in MongoDB using Node.js, Express & Multer

More than Practice:
– Node.js Balance APIs example with Limited, Sequelize & MySQL
– Node.js & JWT – Token Based Authentication & Authorization example
– Dockerize Node.js Express and MySQL example – Docker Compose

Node.js upload/shop epitome in MySQL overview

We're gonna brand a Node.js application like this:

upload-image-mysql-node-js-express-example-ui

Click on Submit push, the file volition be uploaded to MySQL database:

upload-image-mysql-node-js-express-example-database

Nosotros also store the uploaded image in upload folders before saving its information to MySQL.
And then to bank check MySQL prototype data, nosotros salvage the result information in tmp folder.

upload-image-mysql-node-js-express-example-resources

Projection Structure

Let'due south look at our project directory tree:

upload-image-mysql-node-js-express-example-project-structure

db.config.js exports configuring parameters for MySQL connection & Sequelize.
models/index.js: uses configuration above to initialize Sequelize, models/prototype.model.js for Sequelize model Image.
views/alphabetize.html: contains HTML form for user to upload images.
routes/web.js: defines routes for endpoints that is called from views, apply controllers to handle requests.
controllers:

  • domicile.js returns views/index.html
  • upload.js handles upload & store images with middleware function.

middleware/upload.js: initializes Multer Storage engine and defines middleware function.
server.js: initializes routes, runs Express app.

Setup Node.js modules

Open command prompt, change current directory to the root folder of our project.
Install Limited, Multer, Sequelize, Mysql2 with the post-obit command:

          npm install limited multer sequelize mysql2                  

The package.json file will look like this:

          {   "name": "upload-multiple-files-mysql",   "version": "1.0.0",   "description": "Node.js upload images to MySQL database",   "main": "server.js",   "scripts": {     "test": "echo \"Error: no test specified\" && exit ane"   },   "keywords": [     "node",     "upload",     "image",     "mysql"   ],   "author": "bezkoder",   "license": "ISC",   "dependencies": {     "express": "^iv.17.1",     "multer": "^1.4.2",     "mysql2": "^two.1.0",     "sequelize": "^5.21.7"   } }                  

Configure MySQL database & Sequelize

In the src folder, nosotros create a separate config binder for configuration with db.config.js file similar this:

          module.exports = {   HOST: "localhost",   USER: "root",   Countersign: "123456",   DB: "testdb",   dialect: "mysql",   pool: {     max: 5,     min: 0,     acquire: 30000,     idle: 10000   } };                  

First five parameters are for MySQL connection.
puddle is optional, it will be used for Sequelize connectedness pool configuration:

  • max: maximum number of connection in puddle
  • min: minimum number of connection in pool
  • idle: maximum fourth dimension, in milliseconds, that a connection can be idle before beingness released
  • acquire: maximum time, in milliseconds, that puddle will endeavor to get connectedness before throwing error

For more details, please visit API Reference for the Sequelize constructor.

Initialize Sequelize

Now we initialize Sequelize in src/models folder.

Create src/models/index.js with the following code:

          const dbConfig = crave("../config/db.config.js"); const Sequelize = crave("sequelize"); const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {   host: dbConfig.HOST,   dialect: dbConfig.dialect,   operatorsAliases: simulated,   pool: {     max: dbConfig.pool.max,     min: dbConfig.pool.min,     acquire: dbConfig.pool.acquire,     idle: dbConfig.pool.idle,   }, }); const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.images = require("./image.model.js")(sequelize, Sequelize); module.exports = db;                  

We're gonna define Image model in the adjacent footstep.

Define the Sequelize Model

In models folder, create image.model.js file like this:

          module.exports = (sequelize, DataTypes) => {   const Image = sequelize.define("prototype", {     type: {       type: DataTypes.Cord,     },     proper noun: {       type: DataTypes.STRING,     },     information: {       type: DataTypes.Hulk("long"),     },   });   return Image; };                  

This Sequelize Model represents images table in MySQL database. These columns will be generated automatically: id, type, proper noun, data, createdAt, updatedAt.

The data field has Hulk blazon. A Hulk 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:

          const multer = require("multer"); const imageFilter = (req, file, cb) => {   if (file.mimetype.startsWith("image")) {     cb(nothing, true);   } else {     cb("Please upload just images.", simulated);   } }; var storage = multer.diskStorage({   destination: (req, file, cb) => {     cb(nil, __basedir + "/resources/static/assets/uploads/");   },   filename: (req, file, cb) => {     cb(null, `${Date.at present()}-bezkoder-${file.originalname}`);   }, }); var uploadFile = multer({ storage: storage, fileFilter: imageFilter }); module.exports = uploadFile;                  

In the code higher up, we've done these steps:
– First, we import multer module.
– Next, we configure multer to utilise Disk Storage engine.
– Nosotros also define a filter to but allow images to laissez passer.

Yous tin encounter that we have two options here:
destination determines binder to store the uploaded files.
filename determines the name of the file within the destination folder.
– We add together the [timestamp]-bezkoder- prefix to the file'south original name to brand sure that the duplicates never occur.

Create Controller for uploading Images

controllers/upload.js

          const fs = require("fs"); const db = require("../models"); const Epitome = db.images; const uploadFiles = async (req, res) => {   try {     console.log(req.file);     if (req.file == undefined) {       return res.ship(`You lot must select a file.`);     }     Paradigm.create({       blazon: req.file.mimetype,       name: req.file.originalname,       data: fs.readFileSync(         __basedir + "/resource/static/assets/uploads/" + req.file.filename       ),     }).and then((image) => {       fs.writeFileSync(         __basedir + "/resources/static/assets/tmp/" + image.name,         paradigm.data       );       return res.ship(`File has been uploaded.`);     });   } catch (mistake) {     panel.log(error);     return res.send(`Mistake when trying upload images: ${error}`);   } }; module.exports = {   uploadFiles, };                  

Now look at the uploadFiles function:
– First we get and cheque file upload from req.file.
– Next we use Sequelize model create() method to save an Prototype 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, nosotros 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/dwelling house.js

          const path = require("path"); const home = (req, res) => {   return res.sendFile(path.join(`${__dirname}/../views/alphabetize.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:

          <!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-eight" />     <meta proper name="viewport" content="width=device-width, initial-calibration=ane.0" />     <meta http-equiv="X-UA-Compatible" content="ie=border" />     <title>Node.js upload images</championship>     <link       rel="stylesheet"       href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"     />     <style>       div.preview-images > img {         width: thirty%;       }     </fashion>   </caput>   <body>     <div class="container">       <div grade="row">         <div class="col-sm-8 mt-3">           <h4>Node.js upload images - bezkoder.com</h4>           <class             class="mt-four"             action="/upload"             method="POST"             enctype="multipart/form-data"           >             <div class="class-grouping">               <input                 blazon="file"                 name="file"                 id="input-files"                 class="form-control-file border"               />             </div>             <button type="submit" form="btn btn-primary">Submit</button>           </form>         </div>       </div>       <hr />       <div class="row">         <div class="col-sm-12">           <div class="preview-images"></div>         </div>       </div>     </div>     <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>     <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>     <script>       $(document).ready(function() {         let imagesPreview = function(input, placeToInsertImagePreview) {           if (input.files) {             let filesAmount = input.files.length;             for (i = 0; i < filesAmount; i++) {               permit reader = new FileReader();               reader.onload = function(issue) {                 $($.parseHTML("<img>"))                   .attr("src", event.target.consequence)                   .appendTo(placeToInsertImagePreview);               };               reader.readAsDataURL(input.files[i]);             }           }         };         $("#input-files").on("change", function() {           imagesPreview(this, "div.preview-images");         });       });     </script>   </trunk> </html>                  

For HTML office, we create a form with following elements:

  • action="/upload"
  • method="Postal service"
  • enctype="multipart/form-data"

You also need to notice the input tag with the name="file" attribute that we use in the middleware.

The jQuery script shows preview of the called images.
We also use Bootstrap to make the UI more comfortable to read.

Define routes

In routes folder, define routes in web.js with Express Router.

          const express = require("limited"); const router = limited.Router(); const homeController = require("../controllers/domicile"); const uploadController = crave("../controllers/upload"); const upload = require("../middleware/upload"); allow routes = (app) => {   router.get("/", homeController.getHome);   router.post("/upload", upload.single("file"), uploadController.uploadFiles);   render app.utilize("/", router); }; module.exports = routes;                  

There are two routes:
– Become: Dwelling page for the upload form.
– POST "/upload" to call the upload controller. This is for action="/upload" in the view.

The single() role with the parameter is the name of input tag (in html view: <input type="file" proper name="file">) will store the single file in req.file.

Create Limited app server

Finally, we create an Express server.

server.js

          const express = crave("express"); const app = express(); const db = require("./src/models"); const initRoutes = require("./src/routes/web"); global.__basedir = __dirname; app.apply(limited.urlencoded({ extended: true })); initRoutes(app); db.sequelize.sync(); // db.sequelize.sync({ force: true }).then(() => { //   panel.log("Driblet and re-sync db."); // }); let port = 3000; app.heed(port, () => {   panel.log(`Running at localhost:${port}`); });                  

In the code to a higher place, we call Sequelize sync() method.

          db.sequelize.sync();                  

In development, you may need to driblet existing tables and re-sync database. Simply apply force: true as following lawmaking:

                      db.sequelize.sync({ force: true }).and so(() => {   panel.log("Drop and re-sync db."); });                  

Run & Bank check result

Commencement we demand to create tmp and uploads folder with the path resources/static/assets.
On the projection root folder, run this control: node src/server.js

The panel shows:

          Running at localhost:3000                  

Open your browser with url: http://localhost:3000.

Decision

Today we've learned how to upload and store paradigm in MySQL database using limited, multer & sequelize modules. We also built a Residual API with routes for showing the upload form and uploading images with middleware.

Happy learning! See yous again.

Further Reading

  • https://www.npmjs.com/packet/limited
  • https://world wide web.npmjs.com/parcel/multer
  • https://sequelize.org/v3/api/model/

– Upload & resize multiple images in Node.js using Limited, Multer, Precipitous
– How to upload/store images in MongoDB using Node.js, Express & Multer
– Dockerize Node.js Express and MySQL instance – Docker Compose

Source Code

You tin find the consummate source code for this example on Github.

mortimertragivan.blogspot.com

Source: https://www.bezkoder.com/node-js-upload-image-mysql/

0 Response to "how to upload images with slate JS"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel