Skip to main content

Command Palette

Search for a command to run...

Sequelize Image Upload

Published
View as Markdown
  1. Introduction
    To implement image upload with Node.js, Sequelize, and a REST API, you can follow these steps. We'll use a combination of libraries to handle the image upload, store metadata in the database, and manage the backend.
    Requirements -

    Node.js: The runtime environment for executing JavaScript on the server.

    Express.js: A Node.js framework for building REST APIs.

    Sequelize: An ORM for interacting with databases.

    multer: Middleware for handling file uploads.

    MySQL/PostgreSQL/SQLite: A database for storing image metadata (e.g., name, path, etc.).

  2. Set up a Node.js project
    Create a directory for your project and initialize it.

     npm init -y
    

    Install the required dependencies,

     npm install express multer sequelize mysql2
    

    express: For building the API.

    multer: For handling file uploads.

    sequelize: For interacting with the database.

    mysql2: The driver for MySQL (use pg for PostgreSQL or sqlite3 for SQLite).

  3. Set up Sequelize

    Run the Sequelize CLI to set up your project.

     npx sequelize-cli init
    

    This will create the config, models, and migrations directories.

    Update the config/config.json file with your database credentials.

     {
       "development": {
         "username": "root",
         "password": "password",
         "database": "image_upload_db",
         "host": "127.0.0.1",
         "dialect": "mysql"
       }
     }
    
  4. Create an image model

    Create a model to store the image metadata (e.g., filename and path).

     npx sequelize-cli model:generate --name Image --attributes name:string,path:string
    

    Run the migration,

     npx sequelize-cli db:migrate
    
  5. Create the Express app and routes

    Now, set up your Express app and API routes to handle file uploads and saving data in the database.

    app.js

     const express = require('express');
     const multer = require('multer');
     const path = require('path');
     const { Image } = require('./models'); // Sequelize model
    
     const app = express();
    
     // Set up multer for image storage
     const storage = multer.diskStorage({
       destination: function (req, file, cb) {
         cb(null, 'uploads/'); // Directory to store the images
       },
       filename: function (req, file, cb) {
         const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
         cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
       }
     });
    
     const upload = multer({ storage: storage });
    
     // Route to upload an image
     app.post('/upload', upload.single('image'), async (req, res) => {
       try {
         // Save the file metadata in the database
         const image = await Image.create({
           name: req.file.originalname,
           path: req.file.path
         });
    
         res.status(201).json({
           message: 'Image uploaded successfully',
           data: image
         });
       } catch (error) {
         res.status(500).json({ error: 'Failed to upload image' });
       }
     });
    
     // Route to fetch images
     app.get('/images', async (req, res) => {
       try {
         const images = await Image.findAll();
         res.json(images);
       } catch (error) {
         res.status(500).json({ error: 'Failed to retrieve images' });
       }
     });
    
     const PORT = process.env.PORT || 3000;
     app.listen(PORT, () => {
       console.log(`Server is running on port ${PORT}`);
     });
    
  6. Directory Structure

     image-upload-app
     ├── uploads/               # Directory where images are stored
     ├── models/
     │   ├── image.js           # Sequelize model for Image
     │   └── index.js           # Sequelize model index file
     ├── migrations/            # Sequelize migrations
     ├── config/                # Sequelize configuration
     ├── app.js                 # Main app file
     └── package.json
    

    Ensure that you create an uploads/ directory to store the images:

     mkdir uploads
    
  7. Test the API

    Use a tool like Postman or cURL to test the image upload.

    Upload an image,

     POST /upload
     Content-Type: multipart/form-data
     Body: 
       Key: "image" (file)
    

    Fetch all images,

     GET /images
    

    This will return a list of images along with their file paths stored in the database.