04-Apr-2023
.
Admin
Hello Friends,
ReactJS + Node.js Express file/image upload with form data example. In this tutorial, you will learn how to upload a file/image in a ReactJS app with Node.js ExpressJS. For the backend, this tutorial will use a simple Node.js server.
how to file upload using react js and node js is our main topic. it's simple example of react js and node js file upload example. it's simple example of how to upload file using react js and node js steps. I would like to show you the functionality to file upload in node js and react js. Let's see bellow example filie upload in node js and react js.
Create React Frontend App
Step 1: Create React App
Open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2: Install Axios and Bootstrap 4
Then execute the following command to install axios and boostrap 4 library into your react app:
npm install bootstrap --save
npm install axios --save
Add bootstrap.min.cssfile in src/App.js file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
<h2>react node js file upload example</h2>
</div>
);
}
export default App;
Step 3: Create File Upload Form Component
In this step, visit src directory of your react js app and create a form component named FileUpload.js. And add the following code into it:
import React from 'react'
import axios from 'axios';
class FileUpload extends React.Component{
const [file, setFile] = useState();
const [fileName, setFileName] = useState("");
const saveFile = (e) => {
setFile(e.target.files[0]);
setFileName(e.target.files[0].name);
};
const uploadFile = async (e) => {
const formData = new FormData();
formData.append("file", file);
formData.append("fileName", fileName);
try {
const res = await axios.post(
"http://localhost:3000/upload",
formData
);
console.log(res);
} catch (ex) {
console.log(ex);
}
};
render(){
return (
<div className="App">
<input type="file" onChange={saveFile} />
<button onClick={uploadFile}>Upload</button>
</div>
);
}
}
export default FileUpload;
Step 4: Import Component in App.js
In this step, you need to add FileUpload.js file in src/App.js file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import FileUpload from './FileUpload'
function App() {
return (
<div className="App">
<FileUpload/>
</div>
);
}
export default App;
Create Node Express JS Backend
Step 1: Create Node JS App
Open your terminal and execute the following command to create node js app:
mkdir my-app
cd my-app
npm init -y
Step 2: Install Express body parser and cors Dependencies
Execute the following commands to install imperative npm packages which will help us to create REST APIs for your react file upload app:
npm install express cors body-parser express-fileupload
npm install nodemon --save-dev
Step 3: Create Server.js File
In this step, create server.js file and add the following code into it:
const express = require("express");
const fileupload = require("express-fileupload");
const cors = require("cors");
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(fileupload());
app.use(express.static("files"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/upload", (req, res) => {
const newpath = __dirname + "/files/";
const file = req.files.file;
const filename = file.name;
file.mv(`${newpath}${filename}`, (err) => {
if (err) {
res.status(500).send({ message: "File upload failed", code: 200 });
}
res.status(200).send({ message: "File Uploaded", code: 200 });
});
});
app.listen(3000, () => {
console.log("Server running successfully on 3000");
});
Step 4: Start Node JS App
Start the server with the following command and then you can test the form:
npm start
OR
nodemon server.js
#Node JS