Skip to main content

Upload form data with files in ExpressJs using Multer & Mysql

In the previous tutorial, you learn to create /products route with get method of router in Express with Mysql to fetch and filter data using findAndCountAll method.

Now we move on creating APIs to allow client apps to upload form data files using POST and PUT method, and delete rows from database using DELETE method. To upload form data with files, we use Multer library. By using Multer, you can easily upload files to local storage or cloud storage like amazon s3.  Execute the following command to install Multer in to ExpressJs app.

npm install multer

To use Multer, you have to import it into routes/product.routes.js file:

.......
const {Op } = require("sequelize");
const multer = require('multer');

Write the following code to configure Multer to use public folder of the local storage:

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './public');
  },
  filename: function (req, file, callback) {
      callback(null, Date.now().toString() + '-' + file.originalname);
   
  }
});
const upload = multer({ storage : storage }).array('file',2);

We modify original file name by prefixing it with current time and dash. In the array function, you need to specify file field and max count of files to be uploaded. The file field must match the field in form data uploaded by client apps. 

Add more three routes using POST, PUT, and DELETE methods. The post route is to insert data to database, put route to update data, and the delete route to remove data from the database. Sequelize provides convenient methods - create, update, and destroy methods to  perform the tasks.

// upload file to local storage - public folder
router.post("/products", function(req,res){
  upload(req,res,function(err) {
      if(err) {
          return res.end("Error uploading file."+err);
      }  
    // save upload product data to database  
    const { body } = req;
    db.Product.create(
       {
       title:body.title,
       description:body.description,
       price:body.price,
     
      }
     
      ).then(Product =>{
        // save upload image files to database
        let values=[];
        for(const file of req.files) {
          if(file.filename!==undefined){
           
            values.push({fileUrl:file.filename,product_id:Product.id});
          }
        }
   
        db.Image.bulkCreate(values);
        // return success result
        return res.status(200).json({
          message: 'success',
          data: Product,
         });
      }).catch(err => { // return err result
        res.status(500).send({
          message:
            err.message || "Some error occurred while inserting new product"
        });
      });
     
  });  
});
// update product in database
router.put("/products", function(req,res){
   
   
    upload(req,res,function(err) {
      if(err) {
            return res.end("Error uploading file."+err);
        }  
      const { body } = req;
      //console.log("body",body);
      db.Product.update(
         {
         title:body.title,
         description:body.description,
         price:body.price,
       
        },
        {
         where: { id: body.id },
         }
        ).then(async data =>{
          // also update images of the product
          let values=[];
          for(const file of req.files) {
            if(file.filename!==undefined){
             
              values.push({fileUrl:file.filename,product_id:body.id});
            }
          }
          db.Image.bulkCreate(values);
          //
          return res.status(200).json({
            message: 'success',
            data: data,
           });
        })
        .catch(err => {
          res.status(500).send({
            message:
              err.message || "Some error occurred while update the product"
          });
        });
       
    });  
  });

  // delete product by id from database
  router.delete("/products/:id/", function(req,res){
    let pid = [req.params.id];
    console.log("pid=",pid);
    db.Product.destroy({
        where: { id: pid },
     }).then(data =>{
      return res.status(200).json({
        message: 'success',
        data: data,
       });
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while deleting the product"
      });
    });

     
 });

Finally run node app.js to start development server.
Now it is ready to test the APIs. There are various tools to test the APIs to insert, update, and delete data against Mysql database. In this article, we are going to use ARC chrome extension. Thus, you need to add the ARC extension to chrome browser.
From chrome://apps open ARC.



To update a specific record in the database, simply change from method POST to PUT and make sure you include id of the record in text part in the body tab.

To delete a record, you have to choose method DELETE and append slash and id of the record to the Request Url. For example, to delete id-1 record, the Request Url must be written as below:

http://localhost:5000/products/1




Comments

Popular posts from this blog

Get start with React

To start web development with React, i recommend you install Node. Node comes with NPM (package manager) helps you easy to add dependencies, create, start, and build your React apps. You can download and install NPM from its official web site: Download NPM . Another useful tool for coder is Visual Studio Code . On my Windows machine, i have installed Node version 16.10.0 with NPM 7.14.0. Now create a project folder and name it react_tutorials in Drive D: or other drive of your choice. Then open the folder in Visual Studio COde (VSC). From the VSC editor, select Terminal. In the terminal, enter the following command to create my-app app in the project folder created above. D:\react_tutorials>npm init react-app my-app After the my-app app is created successfully. You change to my-app folder (cd my-app) . Then You run " npm start " command to start your first react app on browser. React automatically starts on port 3000.

Why React?

React is one of the top UI development frameworks. It is very popular today among web developers around the globe. I love React because of the following things: - It is simple to learn and use. - It is JavaScript library. - It effectively applies changes to a web page without reloading the page while data changed. - It is easy to find problems or errors while you are coding.

React Express & MYSQL - Full Stack Product Admin Panel

In the earlier tutorials, you learnt to create React app , and API endpoints to do authentication with JWT, protect APIs, get and count rows of MYSQL database, and upload form data with files to the database in ExpressJs. In this tutorial, we continue to develop the React app to build a full stack product admin panel website that accesses ExpressJs API endpoints . The product admin panel app will have a left sidebar that allows a visitor easily to navigate different parts of the app. We use bootstrap to style the app. So run the following command to add bootstrap into the React app. my-app>npm install bootstrap Our form components are from reactstrap and icons from react-icons packages. Let execute the commands below to install reactstrap and react-icons. my-app>npm install reacstrap react-icons To setup the left sidebar in the app, we start by creating the components folder in src folder. To group sidebar files, add sidebar folder to the components folder. We have three sidebar...