如何使用 GridFS 使用 Node.js 和 Mongoose 存储图像

编程入门 行业动态 更新时间:2024-10-21 11:28:54
本文介绍了如何使用 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 存储图像

本文发布于:2023-11-22 19:23:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618700.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   图像   GridFS   Node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!