How to store Images in MongoDB?

How to store Images in MongoDB?

ยท

2 min read

So, you are making a project and you want to store images in MongoDB. Follow these follow steps to do that

1. Use an 'input' take to take a file as input from the user

<input type="file" onChange={handleFileChange} accept='.jpeg, .png, .jpg' />
<button onClick={createNewShip}>Submit</button>

I am using JSX format because I am doing it in React, you can do it in HTML also. I have declared an input tag and a button. The input tag can take only jpeg, png, and jpg files as input.

2. Convert the chosen file into base64 and then use a POST method to upload the base64 into MongoDB

When a file is chosen/changed using the input tag, an onChange handler is called that converts the input file into base64 format, and the state of the name and post is changed.

When the 'Submit' button is clicked, the base64 file is sent to the backend server, which stores the data in MongoDB.

The whole code for the frontend component is given below ๐Ÿ‘‡

import './App.css';
import {useState} from 'react';
import axios from 'axios';

function App() {

  const [post,setPost] = useState("")
  const [name,setName] = useState("")

  async function handleFileChange(e){
    const file = e.target.files[0]
    setName(file.name)
    const base64 = await convertTobase64(file)
    setPost(base64)
  }

  function convertTobase64(file){
    return new Promise((resolve,reject)=>{
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file)
      fileReader.onload=()=>{
        resolve(fileReader.result)
      }
      fileReader.onerror=(err)=>{
        reject(err)
      }
    })
  }

  function createNewShip(){
    axios.post("http://localhost:6060/create-new-post",{name:name,file:post})
      .then(data=>{
        console.log("Success!")
      })
      .catch(err=>{
        console.log("Error!")
      })
  }

  return (
    <div className="App">
    <br/>
      <input type="file" onChange={handleFileChange} accept='.jpeg, .png, .jpg' />
      <br />
      <br />
      <button onClick={createNewShip}>Submit</button>
    </div>
  );
}

export default App;

3. How to show the image in the 'img' tag in HTML?

Just get the base64 string stored in MongoDB using the GET request and set the 'src' attribute to the base64 string, it will automatically show the image.

 <img src={base64} />

Conclusion

This was the whole post. You can share if there are any other ways of storing pictures in MongoDB. I post 2 times a week on Hashnode, so if you want, you can follow me.

Did you find this article valuable?

Support Yash Nirmal by becoming a sponsor. Any amount is appreciated!

ย