我是 Node.js 的新手。谁能给我一个例子,说明如何使用 GridFS 存储和检索二进制数据,例如图像,使用 Node.js 和 Mongoose?我需要直接访问 GridFS 吗?
最佳答案
我对这里评分最高的答案不满意,因此我提供了一个新答案: 我最终使用了 Node 模块 'gridfs-stream' (那里有很棒的文档!)可以通过 npm 安装。 有了它,再加上 Mongoose ,它可能看起来像这样:
var fs = require('fs');
var mongoose = require("mongoose");
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);
function putFile(path, name, callback) {
var writestream = GridFS.createWriteStream({
filename: name
});
writestream.on('close', function (file) {
callback(null, file);
});
fs.createReadStream(path).pipe(writestream);
}
注意path是本地系统上文件的路径。
至于我的文件读取功能,就我而言,我只需要将文件流式传输到浏览器(使用 express):
try {
var readstream = GridFS.createReadStream({_id: id});
readstream.pipe(res);
} catch (err) {
log.error(err);
return next(errors.create(404, "File not found."));
}
关于mongodb - 如何使用 GridFS 使用 Node.js 和 Mongoose 存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135718/