如何使用GridFS来存储使用Node.js和Mongoose的图像 [英] How to use GridFS to store images using Node.js and Mongoose

查看:722
本文介绍了如何使用GridFS来存储使用Node.js和Mongoose的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js的新手任何人都可以提供一个例子,说明如何使用GridFS来存储和检索二进制数据,如图像,使用Node.js和Mongoose?我需要直接访问GridFS吗?

解决方案

我不满意这里最高评价的答案,所以我提供新的一个:
我最终使用节点模块'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);

函数putFile(path,name,callback){
var writestream = GridFS.createWriteStream({
filename:name
});
writestream.on('close',function(file){
callback(null,file);
});
fs.createReadStream(path).pipe(writestream);
}

请注意,路径是本地系统上文件的路径。 p>

对于我的文件的读取功能,对于我的情况,我只需要将文件流式传输到浏览器(使用express):

  try {
var readstream = GridFS.createReadStream({_ id:id});
readstream.pipe(res);
} catch(err){
log.error(err);
return next(errors.create(404,File not found。));
}


I am new to Node.js. Can anyone provide me an example of how to use GridFS for storing and retrieving binary data, such as images, using Node.js and Mongoose? Do I need to directly access GridFS?

解决方案

I was not satisfied with the highest rated answer here and so I'm providing a new one: I ended up using the node module 'gridfs-stream' (great documentation there!) which can be installed via npm. With it, and in combination with mongoose, it could look like this:

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);
}

Note that path is the path of the file on the local system.

As for my read function of the file, for my case I just need to stream the file to the browser (using express):

try {
    var readstream = GridFS.createReadStream({_id: id});
    readstream.pipe(res);
} catch (err) {
    log.error(err);
    return next(errors.create(404, "File not found."));
}

这篇关于如何使用GridFS来存储使用Node.js和Mongoose的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆