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

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

问题描述

我是 Node.js 的新手.谁能为我提供一个示例,说明如何使用 GridFS 存储和检索二进制数据,例如使用 Node.js 和 Mongoose 的图像?我需要直接访问GridFS吗?

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?

推荐答案

我对这里评分最高的答案不满意,所以我提供了一个新答案:我最终使用了节点模块 'gridfs-stream'(那里有很棒的文档!)可以通过 npm 安装.有了它,再加上猫鼬,它可能看起来像这样:

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

注意 path 是文件在本地系统上的路径.

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

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

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天全站免登陆