Skip to content Skip to sidebar Skip to footer

Stuck At Changing Binary Data To Base64 (gridfs-stream)

I am trying to change some binary data from my uploaded images to base64 so I can use that to display an image. But the terimal is giving me this error: TypeError: Cannot read pro

Solution 1:

I am also looking for the solution to read the image from gridfs and i am using grid-fs strem

this is the solution I found, hope it is helpful for you.

// set up the gridfs

import mongoose from'mongoose';
importGridfrom'gridfs-stream';

const db = mongoose.connection.db;
const mongoDriver = mongoose.mongo;
const gfs = newGrid(db, mongoDriver);

// write the image to mongo

const writeStream = gfs.createWriteStream({
  filename: 'test.png',
  content_type: 'image/png',
});
fs.createReadStream(filePath).pipe(writeStream);

writeStream.on('close', (gfsFile) => {
  // remove the original file
  fs.unlink('test.png');
  // this is the information, and _id is the id console.log(gfsFile);
});

// read the image to mongo

const readstream = gfs.createReadStream({
  _id: id,
});

const bufs = [];
readstream.on('data', function (chunk) {
  bufs.push(chunk);
});
readstream.on('end', function () {
  const fbuf = Buffer.concat(bufs);
  const base64 = fbuf.toString('base64');
  console.log(base64);
});

Solution 2:

Please check this Github repo i've created to upload images and return back result as base64. https://github.com/houssem-yahiaoui/fileupload-nodejs.

Post a Comment for "Stuck At Changing Binary Data To Base64 (gridfs-stream)"