개발

MOGODB Insert/Select Image File — NodeJS

쩌비군 2020. 6. 4. 18:59
728x90

 

NodeJS에서 MogoDB 에 File 을 Insert 하고 Select 하여 Image Src 에 설정하는 방법은 아래와 같습니다.

 

MongoDB 에 Binary 로 데이터를 입력하고 Binary 를 읽어서 Img Src 에 입력하면 되는 단순한 작업인데, 의외로 잘 안되는 경우가 많습니다. 그 이유는 MongoDB 에 Binary 로 입력하는 방식과 입력한 Binary 를 읽어올 때의 Encoding, Decoding 이 달라서 생기는 경우가 대부분입니다.

 

아래의 코드를 보시면서 그 부분을 참고 하시면 됩니다.

 

1.Insert Image File To MongoDB

const { MongoClient, Binary } = require('mongodb');
const assert = require('assert');
const { dbURL, dbName, collectionName } = require('../Mongoose/config');
const fs = require('fs');

// Connect to the server
MongoClient.connect(dbURL, (err, client) => {
  assert.equal(null, err);
  console.log('Connected successfully to server');

  const db = client.db(dbName);
  const collection = db.collection(collectionName);

  const item = {};
  item.title = '제목' 
  item.images_1 = fs.readFileSync(`image.jpg`).toString('base64');
  collection.insertOne(item, (err, result) => {
   if (err) {
       console.log(err);
   } else {
    console.log('Documents inserted!');
   }
 });
client.close();
});

 

 

2. Select Image File From MongoDB

2–1. JS Function

_imageEncode(imageBuffer) {
  const mimetype = 'image/jpeg';
  return `data:${mimetype};base64,${imageBuffer}`;
}

 

2–2. HTML Image Src

<img id="row-item" class="row-item-img-image" align="center"
     :src="this._imageEncode(imageBuffer)"
     :alt="propItem.title">