Heim > Fragen und Antworten > Hauptteil
黄舟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>
亲测成功。
代码写的有点仓促,有很多可以优化的地方,你自己可以改进,我只是提供一个参考给你,希望对你有帮助