How to send base_64 Image in ReactJS

We can send base_64 Image in ReactJs with help of the Javascript method. How to store base_64 Image in ReactJS.

I will use Nodejs for storing base_64 Image into a database. So Node js will handle our React Request.

Base64 also known as Base64 Content-Transfer-Encoding is an encoding and decoding technique used to convert binary data to an American Standard for Information Interchange (ASCII) text format, and vice versa.

Our Nodejs code block Which will handle ReactJS Request

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import Post from "../models/post.js";

const app = express();
app.use(express.json({limit: '25mb'}));
app.use(express.urlencoded({limit: '25mb', extended: true}));
app.use(cors());

app.use("/uploads", async (req, res, next) => {
  const body = req.body;
  try {
    const newImage = await Post.create(body);
    newImage.save();
    res.status(201).json({message: "new image uploaded", createdPost: newImage});
  } catch (error) {
    res.status(409).json({
      message: error.message,
    });
  }
};);

 mongoose.connect('mongodb://localhost/imageUpload', { useUnifiedTopology: true ,  useNewUrlParser: true})
.then(console.log('database connected'))
.catch(err => err)

const PORT = 5000;
app.listen(PORT, () => {
  console.log("listening at port " + PORT);
});

At this point, we are done with the server. So we’ll start our server by using the command below:

node index.js

Now We will go to the Front-end part ( With React JS )

Creating Our React App ( We are using Axios for sending our request, You can use fetch too )

import React, { useState } from "react";
import axios from "axios";

export default function ImageUploader() {
  const [postImage, setPostImage] = useState({
    myFile: "",
  });

const url = "http://localhost:5000/uploads";
const createImage = (newImage) => axios.post(url, newImage);

  const createPost = async (post) => {
    try {
      await createImage(post);
    } catch (error) {
      console.log(error.message);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    createPost(postImage);
  };

  const convertToBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) => {
        reject(error);
      };
    });
  };
  const handleFileUpload = async (e) => {
    const file = e.target.files[0];
    const base64 = await convertToBase64(file);
    setPostImage({ ...postImage, myFile: base64 });
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="file"
          label="Image"
          name="myFile"
          accept=".jpeg, .png, .jpg"
          onChange={(e) => handleFileUpload(e)}
        />

        <button>Submit</button>
      </form>
    </div>
  );
}

We are saving our data into MongoDB DATABSE. You can save it into PHPMYADMIN or any other database.

See our More Project in Laravel and ReactJS

Theme Color change in React JS

Records display in Material UI Table

Display Records in Model Box in React

Responsive Navbar in Material UI React

Upload PDF file in React, Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *