node.js - express 中怎样把grid-fs中存储的图片,显示在网页上?
黄舟
黄舟 2017-04-17 15:17:59
0
1
680

express 中怎样把grid-fs中存储的图片,显示在网页上?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
黄舟

Show image in GridFS in front-end using express

mongo preparation

  • Start your mongo service, mongod --dbpath ~/mongodb_Data (replace ~/mongodb_Data with your own path)

  • Use mongofiles -d test put /Users/taozhi/Pictures/bg/21.jpg to add a picture to gridfs, and replace the image path /Users/taozhi/Pictures/bg/21.jpg with your own. After the addition is successful, you will get the following prompt:

    2016-11-03T11:18:42.851+0800    connected to: localhost
    added file: /Users/taozhi/Pictures/bg/21.jpg
    
  • mongoConnect to the default mongo server, db.fs.files.find()you can see the information of the image just stored, including file name, file size, block size, time and MD5 check code, etc.

    {
    "_id": ObjectId("581aad5aa3205aa0b201aceb"),
    "chunkSize": 261120,
    "uploadDate": ISODate("2016-11-03T03:22:02.621Z"),
    "length": 218155,
    "md5": "f4f93cef162e5b863f79a5187644e856",
    "filename": "/Users/taozhi/Pictures/bg/21.jpg"
    }
  • According to the _id of the file, query all the chunks in the fs.chunks collection, db.fs.chunks.find({files_id:ObjectId('581aad5aa3205aa0b201aceb')})

The data preparation work is almost done here, let’s write the application service!

  • Or you can also use GridFS's writeFile directly. The detailed code can be seen below

node service

The service is divided into several steps

  • If it is a set of processes, read the file

  • Write to mongo

  • Read data during service

  • Return to frontend

Because what you requested is a picture, let me read the file data here, base64 encode it and return it to the front end, and you can see the picture

app.js

const fs = require('fs')
const bodyParser = require('body-parser')
const express = require('express')
const path =  require('path')
const http = require('http')
const Db = require('mongodb').Db,
      MongoClient = require('mongodb').MongoClient,
      Server = require('mongodb').Server,
      ObjectID = require('mongodb').ObjectID,
      GridStore = require('mongodb').GridStore,
      Grid = require('mongodb').Grid;

const db = new Db('test', new Server('localhost', 27017));
const app = express();
const server = http.createServer(app);

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname));

app.use(express.static(path.join(__dirname, '../../')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/gridfs', (req, res) => {
// Establish connection to db
  db.open(function(err, db) {
    // Our file ID
    var fileId = new ObjectID();

    // Open a new file
    var gridStore = new GridStore(db, fileId, 'w');

    // Read the filesize of file on disk (provide your own)
    var fileSize = fs.statSync('/Users/taozhi/Pictures/bg/21.jpg').size;
    // Read the buffered data for comparision reasons
    var data = fs.readFileSync('/Users/taozhi/Pictures/bg/21.jpg');

    // Open the new file
    gridStore.open(function(err, gridStore) {

      // Write the file to gridFS
      gridStore.writeFile('/Users/taozhi/Pictures/bg/21.jpg', function(err, doc) {

        // Read back all the written content and verify the correctness
        GridStore.read(db, fileId, function(err, fileData) {
          res.render('index.ejs', { data: data.toString('base64') });
          db.close();
        });
      });
    });
  });
})

app.use((err, req, res, next) => res.status(500).json({err: err.toString()}))

app.use((req, res) => res.status(404).json({ isError: true, error: { message: 'router NOT FOUND' } }))

server.listen(3333, '0.0.0.0', err => {
  if(err) return console.error('app start failed')
  console.info('app start at %s', 3000)
})

index.eje

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
  <img src=<%= "data:image/jpg;base64,"+data %> />
</body>
</html>

Personal test was successful.

The code was written a bit hastily, and there are many areas that can be optimized. You can improve it yourself. I just provide a reference for you. I hope it will be helpful to you

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template