黄舟2017-04-17 15:19:59
啟動你的mongo服務, mongod --dbpath ~/mongodb_Data
(~/mongodb_Data替換成你自己的路徑)
利用mongofiles -d test put /Users/taozhi/Pictures/bg/21.jpg
加入一張圖片到gridfs
中,圖片路徑/Users/taozhi/Pictures/bg/21.jpg 替換成你自己的。加入成功後,會得到以下提示:
2016-11-03T11:18:42.851+0800 connected to: localhost
added file: /Users/taozhi/Pictures/bg/21.jpg
mongo
連上預設的mongo server,db.fs.files.find()
可以看到剛剛儲存的圖片的信息,包括檔案名,檔案大小,區塊大小,時間和MD5校驗碼等
{
"_id": ObjectId("581aad5aa3205aa0b201aceb"),
"chunkSize": 261120,
"uploadDate": ISODate("2016-11-03T03:22:02.621Z"),
"length": 218155,
"md5": "f4f93cef162e5b863f79a5187644e856",
"filename": "/Users/taozhi/Pictures/bg/21.jpg"
}
根據文件的_id, 查詢fs.chunks集合裡面所有的chunks,db.fs.chunks.find({files_id:ObjectId('581aad5aa3205aa0b201aceb')})
資料的準備工作到這裡就差不多了,接著寫應用服務吧!
或直接使用GridFS的writeFile同樣可以,詳細程式碼可以看下面
服務分幾步
如果是一套流程的話,讀取檔案
寫入mongo
服務的時候讀出資料
返回前端
因為你要求的是圖片,那我這裡就讀出文件數據,base64編碼回前端就可以看到圖片了
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>
親測成功。
程式碼寫的有點倉促,有很多可以優化的地方,你自己可以改進,我只是提供一個參考給你,希望對你有幫助