file upload using multer
Tue Oct 31 2023 08:39:04 GMT+0000 (Coordinated Universal Time)
Saved by @Ajay1212
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)); //// for only name cb(null, 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}) }); }); ///////////////////////////// post array in image const uploadFoodImage = async (req, res, next) => { try { const filenames = req.files.map((file) => file.filename); const newdata = await FoodImage.create({ images: filenames }); newdata.save() .then(() => { res.status(201).json({ status: "success", newdata: newdata, }); }) .catch((error) => { res.status(500).json({ error: error.message }); }); } catch (error) { res.status(500).json({ error: error.message }); } }; /////////////////////////////////////////////////////////// //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 }) }); }); //////////////////////////////// for array in set image const updateImage = async (req, res) => { const _id = req.params.id; const imageIndex = req.params.index; try { const existingData = await FoodImage.findById(_id); if (!existingData) { return res.status(404).json({ status: "error", message: "Image not found", }); } if (imageIndex < 0 || imageIndex >= existingData.images.length) { return res.status(400).json({ status: "error", message: "Invalid image index", }); } if (req.file) { const newImageFilename = req.file.filename; existingData.images[imageIndex] = newImageFilename; } await existingData.save(); res.status(200).json({ status: "success", data: existingData, }); } catch (error) { res.status(500).json({ status: "error", 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; ////////////////////////////////////////////////////////// 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; app.use('/public/images',express.static(path.join(__dirname, 'public/images')));
Comments