Skip to main content

Multiple Image Uploads in React JS with NodeJs And MongoDB

In this blog we will discuss Multiple Image Uploads in React JS with NodeJs And MongoDB.

For the frontend we will have an Input tag with multiple attribute to take multiple inputs in React JS

example -

  <input
        onChange={(e) => {
          setImage(e.target.files)
        }}
        multiple
        type="file"
      />

We will the bind the onChange method with the state to save the e.target.files (FileList Array)

const [image, setImage] = useState([])

We will create a button to handle API submit

   <button onClick={handleSubmit}> SUBMIT</button>

So the code on App.js Becomes :

import { useState } from "react"
import axios from 'axios'

function App() {

  const [image, setImage] = useState([])
  const [category, setCategory] = useState('electronics')
  console.log(image)

  const handleSubmit = () => {

    let formData = new FormData()
    formData.append('category', category)
    Array.from(image).forEach(item => {
      formData.append('products', item)
    })
    const url = 'http://localhost:5000/image'
    axios.post(url, formData).then(result => {
      console.log(result)
    }).catch(err => {
      console.log(err)
    })
  }

  return (
    <div>

      {
        Array.from(image).map(item => {
          return (
            <span>
              <img
                style={{ padding: '10px' }}
                width={150} height={100}
                src={item ? URL.createObjectURL(item) : null} />
            </span>
          )
        })
      }

      <input
        onChange={(e) => {
          setImage(e.target.files)
        }}
        multiple
        type="file"
      />
      <input
        onChange={(e) => setCategory(e.target.value)}
        type="text" value={category}
      />
      <button onClick={handleSubmit}> SUBMIT</button>
    </div>
  )
}

export default App

Note -  Axios should be installed.


This is frontend part now we will discuss backend.

In the Node JS Part, we will use following packages :

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const cors = require('cors')
const multer = require('multer')
var path = require('path')

And use them with configs like : 

In the last the index.js file becomes : 

const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const cors = require('cors')
const multer = require('multer')
var path = require('path')

var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/')
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
})

var upload = multer({ storage: storage });
// const upload = multer({ dest: 'uploads/' })

const app = express()

app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static('public'))

mongoose.connect('mongodb://localhost:27017/test', (err) => {
    if (err) {
        console.log('DB Err.')
    } else {
        console.log('DB Connected.')
    }
});

const ProductModel = mongoose.model('prod', {
    category: { type: String },
    images: { type: Array, },
});

app.post('/image', upload.array('products', 12), (req, res) => {
    console.log(req.body, 21)
    console.log(req.files, 21)
    let result = ProductModel.create({
        category: req.body.category,
        images: req.files
    })
    if (result) {
        res.send({ code: 200, message: 'Upload Success' })
    } else {
        res.send({ code: 500, message: 'Upload Err' })
    }
})

app.get('/image', async (req, res) => {
    let products = await ProductModel.find({})
    if (products.length > 0) {
        res.send({ code: 200, data: products })
    } else {
        res.send({ code: 500, message: 'Server Err' })
    }
})


app.listen(5000, () => {
    console.log(`Backend Running At Port 5000`)
})

we created a simple modal to save the category and images in the products array.

In this way we can set and get images using node js.

Follow my youtube channel for detailed video on this topic.





Thank you and let me know any issues you face.



Comments

Popular posts from this blog

Shopping Cart React.js Project with Explanation✅ [ Simple Ecommerce Website using Reactjs ]

Hello guys in this video we will discuss shopping cart web app.  first we need to install the basic react app using - npx create-react-app app-name The folder structure should be containing three files  in components folder as below : In App.js :  import './App.css' ; import Header from './components/Header' ; import ProductList from './components/ProductList' ; import CartList from './components/CartList' ; import { useState } from 'react' ; function App () {   const [ product , setProduct ] = useState ([     {       url : 'https://rukminim1.flixcart.com/image/300/300/l51d30w0/shoe/z/w/c/10-mrj1914-10-aadi-white-black-red-original-imagft9k9hydnfjp.jpeg?q=70' ,       name : 'TRQ White Shoes' ,       category : 'Shoes' ,       seller : 'AMZ Seller Ghz' ,       price : 1999     },     {       url : 'https://5.imimg.com/data5/KC/PC...

Create A Date Range Picker in React JS (By Saifi Code)

 To Create  A Date Range Picker in React JS , need to install following packages :  npm i antd npm i moment Step 1 : import DatePicker from antd and get RangePicker from this package Step 2 : In the JSX Use the package , you will start get picker ui Example :  To get the values use onChange method and save values in state  Try to console the state to check if the values are updating App.js File : import 'antd/dist/antd.css' ; import { DatePicker } from 'antd' ; import { useState } from 'react' ; import moment from 'moment' ; const { RangePicker } = DatePicker ; function App () {   const [ dates , setDates ] = useState ([])   console . log ( dates )     return (     < div style = { { margin : 20 } } >       < RangePicker         onChange = { ( values ) => {                     setDates ( values . map ( item => { ...

MERN Authentication - Login, Register, Verification Email, Forget Password, User Name & Logout on Navbar

In The React Side :  The folder structure will be : Lets start from App.js  On this file we will be adding routing , install the package react-router-dom : import './App.css' ; import React from 'react' ; import {   BrowserRouter as Router ,   Routes ,   Route ,   Link } from "react-router-dom" ; import Signup from './components/Signup' ; import Signin from './components/Signin' ; import Home from './components/Home' ; import ForgetPassword from './components/ForgetPassword' ; import NewSubmit from './components/NewSubmit' ; function App () {   return (     < div >       < Router >         < Routes >           < Route path = "/signup" element = { < Signup /> } />           < Route path = "/signin" element = { < Signin /> } />           < Route path = "/" e...