article

Saturday, September 9, 2023

React JS Node Express Upload File

React JS Node Express Upload File

https://expressjs.com/
Express JS
Fast, unopinionated, minimalist web framework for Node.js

Install
$ npm install express --savev PS C:\nodeproject> npm install express --save
https://expressjs.com/en/starter/hello-world.html

cors
CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
https://www.npmjs.com/package/cors
PS C:\nodeproject>npm i cors

run PS C:\nodeproject> node index.js
//index.js
const express = require('express')
const cors = require('cors')
const multer = require('multer') //http://expressjs.com/en/resources/middleware/multer.html npm install --save multer

const app = express()
app.use(cors())
app.use(express.json())

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    return cb(null, "./public/images")
  },
  filename: function (req, file, cb) {
    return cb(null, `${Date.now()}_${file.originalname}`)
  }
})

const upload = multer({storage})

app.post('/upload', upload.single('file'), (req, res) =>> {
  console.log(req.body)
  console.log(req.file)
  return res.json({Status: "Success"});
})

app.listen(3001, () => {
  console.log("Server is running")
})
run postman post: http://localhost:3001/upload React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app my-app

Run
C:\react-js\my-app> npm start

C:\react-js\my-app\src\App.js
//C:\react-js\my-app\src\App.js 
import React, { useState } from "react"
import axios from 'axios'

function App() {
  const [file, setFile] = useState()
  const [msg, setMsg] = useState("");
  
  const upload = () => {
    const formData = new FormData()
    formData.append('file', file)
    axios.post('http://localhost:3001/upload',formData )
    .then((response) => {
        console.log(response);
        if(response.data.Status === 'Success') {
            setMsg("File Successfully Uploaded");
        }else{
            setMsg("Error");
        }
    })
    .catch(er => console.log(er))
  }
   return (
    <div className="container" style={{paddingTop: 60}}>
		<div className="row d-flex justify-content-center align-items-center h-100">
		  <label className="form-label">Upload File</label>
		  <input className="form-control form-control-lg" type="file" onChange={(e) => setFile(e.target.files[0])}/>
		</div>
		
      <button type="button" className="btn btn-primary btn-lg" onClick={upload} style={{marginTop: '20px'}}>Upload</button>
	  <p><h1 style={{fontSize: '15px', textAlign: 'center', marginTop: '20px'}}>{msg}</h1></p>
    </div>
  )
}

export default App;
Run C:\react-j\my-app>npm start
http://localhost:3000/

Related Post