DEV Community

Saksham Gupta
Saksham Gupta

Posted on

Upload and handle file in ReactJs and NodeJs using FormData.

Upload and handle file from ReactJs and NodeJs using FormData.

Introduction

You may not have ever handled file uploads in React or any other technologies, but there is a high possibility you’ll encounter the need for it, whether tor update profile photos of users, CSV files, or PDFs, to mention but a few. In this guide, you’ll learn how to upload files in your React apps(Frontend) to NodeJs(Backend).

Set Up an App

To get started, run the following command in your terminal or visit React to get a fully configured React development environment via Sandbox

npx create-react-app <YOUR_APP_NAME>
Enter fullscreen mode Exit fullscreen mode

refers to your preferred app name.

Next, create a simple component that has a file input with an upload button.

import { useState } from "react";
import "./../App.css";
const FileUpload = () => {
 const [selectedFile, setSelectedFile] = useState();
 const [isFilePicked, setIsFilePicked] = useState(false);
 const changeHandler = (event) => {
  setSelectedFile(event.target.files[0]);
  event.target.files[0] && setIsFilePicked(true);
 };
 const handleSubmission = () => {
  // HANDLING FILE AS SENDING FILE INTO BACKEND
  if (!isFilePicked) return;
  const formData = new FormData();
  formData.append("File", selectedFile);
   // ALSO ADD RANDOM VALUE IF YOU WANT LIKE STRING , OBJECT OR      ARRAY
  formData.append("carDetail", {
   car: "honda",
   engine: "1498 cc",
   fuel_Type: "Petrol & Diesel",
 });
// API CALL
 fetch("http://localhost:3001/", {
  method: "POST",
  body: formData,
 })
 .then((response) => response.json())
 .then((result) => {
  console.log("Success:", result);
 })
 .catch((error) => {
   console.error("Error:", error);
  });
 };
return (
 <div className="App">
 <input type="file" name="file" onChange={changeHandler} />
  <div>
   <button onClick={handleSubmission}>Submit</button>
  </div>
 {isFilePicked ? (
 <div>
  <p>Filename: {selectedFile.name}</p>
  <p>Filetype: {selectedFile.type}</p>
  <p>Size in bytes: {selectedFile.size}</p>
  <p>
   lastModifiedDate:{" "}
   {selectedFile.lastModifiedDate.toLocaleDateString()}
  </p>
 </div>
 ) : (
 <div>
  <p>Select a file</p>
  </div>
 )}
 </div>
 );
};
export default FileUpload;
Enter fullscreen mode Exit fullscreen mode

Network Response Will be like:

  • File will be in binary. Alt Text

Next, create a Backend with mongodb which will recieve FormData from frontend and process it

var express = require(“express”);
const upload = require(“express-fileupload”);
var cors = require(“cors”);
var app = express();
//MIDDLEWARES
app.use(upload());
app.use(cors());
//ROUTE DEFINE
app.post(“/”, async function (req, res) {
 try {
  // IN REQ.FILES.”YOUR_FILE_NAME” WILL BE PRESENT
  const file = req.files;
  const bodyData = req.body;
  // console.log(file);
  // console.log(bodyData);
  res.status(200).send({
  message: “FILE RECEIVED!”,
 });
 } catch (error) {
 res.send(“ERROR”);
 }
});
var PORT = 3001;
app.listen(PORT, function () {
 console.log(“Server is running on PORT:”, PORT);
});
Enter fullscreen mode Exit fullscreen mode
Conclusion

For refernce i have added my github repo so you can clone it also look into code deeply.
Github Repo.
Thank You.

Latest comments (0)