Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

node.js - Reading binary files from MongoDB

I am working on a project currently that involves uploading images and videos and then save them to MongoDB. I am using multer and GridFs to achieve this. The images and videos are saved in Binary format. Now, I have a little problem, I want to be able to open the image files and do some image manipulation using Jimp, but I don't know how to achieve this.

This is what is returned from the database i.e fs.chunk collection

found: {
    _id: 5ff5fe1f6461621e34f124d5,
    files_id: 5ff5fe1f6461621e34f124d4,
    n: 0,
    data: Binary {
      _bsontype: 'Binary',
      sub_type: 0,
      position: 261120,
      buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 48 00 48 00 00 ff e2 0c 58 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 0c 48 4c 69 6e 6f 02 10 00 00 ... 261070 more bytes>
    }
  }

This is what is stored in the fs.files collection

fieldname: 'avatar',
  originalname: 'CMG - Bright Future Blaze.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  id: 5ff5fabcbcd9bb26c8896ce6,
  filename: 'ef96af4bd209f827963aa9580196e453.jpg',
  metadata: null,
  bucketName: 'uploads',
  chunkSize: 261120,
  size: 391319,
  md5: '10782da2083a3f1f201ba6f33748da62',
  uploadDate: 2021-01-06T18:00:28.382Z,
  contentType: 'image/jpeg'

From the snippet above, the filename is listed there, but my issue is actually getting to open this file and do some image manipulation. Any help would be appreciated. If I try to convert the binary data using data.toString('base64') it outputs [object ArrayBuffer]

question from:https://stackoverflow.com/questions/65602354/reading-binary-files-from-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The data property is actually a ArrayBuffer instead of a Buffer. If you reference the docs on Buffer. You should be able to do

Buffer.from(data).toString('base64')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...