Home > Back-end >  Convert image buffer type toString('encode64') from express nodejs and save in mongodb
Convert image buffer type toString('encode64') from express nodejs and save in mongodb

Time:07-19

with react I recover a buffer which already saved in mongodb with multer by expressJS and I convert it to base64 to display it as an image, it works fine.

 axios
      .get("http://localhost:5000")
      .then((res) => setData(res.data))
      .catch((err) => console.log(err, "it has an error"));
  }


 data.map((singleData) => {
       // const base64String =btoa(String.fromCharCode.apply(null, new Uint8Array(singleData.img.data.data)));
       const Stringbuffer = new Buffer(singleData.img.data.data).toString("base64");
       console.log(singleData);
   
        return <img src={`data:image/png;base64,${Stringbuffer}`} alt="profile" width="300"/>
      }
    

Now i want to save image as base64 string from server to retrieve it as base64 string in react by using new Buffer().toString('base64') in server and not in frontend ,,but when i show it in the console from server it seem not a buffer object like the console of react.

this is the frontend console this is the frontend console

[![enter image description here][2]][2]

this is backend console [2]: https://i.stack.imgur.com/825CU.jpg

this is my backend code :

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/");
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  },
});

const upload = multer({ storage: storage });

app.use(cors())
app.post("/", upload.single("file"), (req, res) => {
 const binaryData = fs.readFileSync("uploads/"   req.file.filename);
 var base64data = Buffer.from(binaryData, 'binary').toString('base64');
 
  //console.log(base64data)
  const saveImage =  imageModel({
    img: {
      data: fs.readFileSync("uploads/"   req.file.filename),
      image: base64data,
      contentType: "image/png",
    },
  });
  saveImage
    .save()
    .then((res) => {
      console.log("image is saved");
    })
    .catch((err) => {
      console.log(err, "error has occur");
    });
    res.send('image is saved')
});


app.get('/',async (req,res)=>{
  const allData = await imageModel.find()
  console.log(allData);
  res.json(allData)
})

CodePudding user response:

I want save the upload image from server like base64 string by using new Buffer() to display that directly without doing new Buffer() in frontend by using <img src={data:image/png;base64,${Stringbuffer}}

CodePudding user response:

why even store the image in the database, use multur to keep it in your server files and add the path of that file to your database, when requesting from the frontend you only have to send the link (path) of the image to the img tag

  • Related