FILE UPLOAD USING MULTER

Project
Document

Multer is a middleware for handling file uploads in Node.js. It is commonly used in the MERN (MongoDB, Express.js, React, and Node.js) stack to handle file uploads in web applications.

In a MERN stack, Multer is typically used in the Express.js backend to handle file uploads from the React frontend. When a user submits a file through a form on the React frontend, the form data is sent to the Express.js backend. Multer intercepts the request and parses the file data, storing it on the server’s file system.

NODE JS

var express = require('express');
var Product = require("../models/productSchema");
var router = express.Router();
const multer = require("multer");
const{v4:uuidv4} = require("uuid");
const path = require("path");

var storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null,'public/images/');
  },
  filename: (req, file, cb) => {
    
        console.log("MULTER ENTRY ",file.originalname)
        cb(null,uuidv4() + '_' + Date.now() + path.extname(file.originalname));       
      
  },
});

const fileFilter=  (req, file, cb) => {
      if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
          cb(null, true);
      } else {
          cb(null, false);
          return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
      }
  }
  let upload= multer({ storage,fileFilter});

router.route('/createproduct').post( upload.single("image"),  async (req, res, next) => {
 
    const name= req.body.name;
    const price= req.body.price;
    const discription= req.body.discription;
    const image= req.file.filename;

    const newuserdata ={
      name,price,discription,image
    } 
    const newdata = await new Product(newuserdata);
    newdata.save()
            .then(()=>{
              res.status(201).json({
                status:"success",
                newdata:newdata 
              })
            })
              .catch ((error)=>{
                res.json({error})
              });
});

//get data

  router.route('/getproduct') .get( async (req, res) => {
    try {
      const newdata = await Product.find(req.body);
      
      res.status(200).json({
        status:"success",
        newdata
      })
    } catch (error) {
      res.json({
        error
      }) 
    }
      
    });

    //get single data

   
    router.get('/getproduct/:id', async(req, res) => {
      try {
        const data = await Product.findById(req.params.id);
        
        res.status(200).json({
          status:"success",
          data
        })
        
      } catch (error) {
        res.json({
          error
        })
      }     
      });

      //update product

router.route('/getproduct/:id').patch( upload.single("image"),  async (req, res, next) => {      
            const _id=  req.params.id;
        
        if(req.file){
          var productdata={
            name:req.body.name,
            price:req.body.price,
            discription:req.body.discription,
            image:req.file.filename
          }}
        else{
          var productdata={
            name:req.body.name,
            price:req.body.price,
            discription:req.body.discription,
          }}
  
        const data = await Product.findByIdAndUpdate(_id,productdata);
          data.save()
          .then(()=>{
            console.log("ajay");
            res.status(201).json({
              status:"success",
              data:data
            })
          })
            .catch ((error)=>{
              res.json({
                error: error.message 
              })
            });
        });
        
      //delete product

      router.delete("/deleteproduct/:id",async(req,res)=>{
        try {
          const _id = req.params.id;
          const singledata = await Product.findByIdAndDelete(_id);
          res.send(singledata);
          
        } catch (error) {
          res.status(500).send(error);
        }
      });

 module.exports = router;

REACT CODE


import React,{useState} from 'react'
import './admin.css';
import axios from "axios";
import { useNavigate } from 'react-router';
const Addproduct = () => {

  const [user,setuser]=useState({
    name:"",
    price:"",
    discription:"",
    image:""
  });
  const navigate = useNavigate("");
  const handelchange =(e)=>{
    setuser({...user,[e.target.name]:e.target.value})}
const handelimage =(e)=>{
  setuser({...user,image:e.target.files[0]});}

  const submit = async (e) =>{
     e.preventDefault();
 const formdata = new FormData();
   
    formdata.append("name", user.name);
    formdata.append("price", user.price); 
    formdata.append("discription", user.discription);
    formdata.append('image', user.image);
  
    console.log("formdata",formdata);
  
await axios.post("http:///127.0.0.1:5000/adproduct/createproduct",
        formdata)

    .then( (response) => { 
      console.log(response,"response");
        navigate("/viewproduct");     
       //do something awesome that makes the world a better place
    }).catch(function (error) {
      // handle error
      console.log(error);
    })
  };  

  return (
    <>
    <div className='addp'>
      <div className="card card-primary">
        <div className="card-header">
          <h3 className="card-title">Add product</h3>
        </div>
        <form  enctype="multipart/form-data">
          <div className="card-body">
            <div className="form-group">
              <label htmlFor="exampleInputEmail1">product name</label>
              <input type="text" className="form-control" id="exampleInputEmail1" name='name' value={user.name} onChange={handelchange}/>
            </div>
            <div className="form-group">
              <label htmlFor="exampleInputPassword1">product price</label>
              <input type="text" className="form-control" id="exampleInputPassword1" name='price'  value={user.price} onChange={handelchange}/>
            </div>
            <div className="form-group">
              <label htmlFor="exampleInputPassword1">image</label>
              <input type="file" className="form-control" id="exampleInputPassword1" multiple accept=".png, .jpg, .jpeg" name='image'  onChange={handelimage}/>
            </div> 
            <div className="form-group">
              <label htmlFor="exampleInputPassword1">discription</label>
              <input type="text" className="form-control" id="exampleInputPassword1"  name='discription' value={user.discription} onChange={handelchange}/>
            </div>
          </div>
          <div className="card-footer">
            <button type="button" className="btn btn-primary" onClick={submit}>Submit</button>
          </div>  
        </form>
      </div>
    </div>
    </>
    
  )
}

export default Addproduct;

LOGIN API

Leave a Comment