这是我的 express.js 代码,用于将文件上传和下载到 GridFS:
var fs = require("fs");
var gridStream = require("gridfs-stream");
var mongoose = require("mongoose");
exports.init = function(app, db)
{
var grid = gridStream(db, mongoose.mongo);
app.post("/UploadFile", function(request, response)
{
var file = request.files.UploadedFile;
var meta = request.param("Meta");
var name = request.param("Name");
var stream = grid.createWriteStream(
{
filename: name,
metadata: meta
});
fs.createReadStream(file.path)
.on("end", function()
{
response.send({ Success: true });
})
.on("Error", function(error)
{
HandleError(error, response);
})
.pipe(stream);
});
app.get("/DownloadFile", function(request, response)
{
var selector = request.param("Selector");
response.writeHead(200, { "Content-Type" : "image/png"});
grid.createReadStream({ filename: "FileUploadNamed" }).pipe(response);
});
}
它工作得很好,但我想指定一个要读取和写入的存储桶,但我不知道该怎么做。我已经在网上看到了调用 GridFS 构造函数的示例,但正如您所看到的,我在这里没有这样做。该文档还说可以提供不同的存储桶名称,但我没有看到任何有关如何提供的信息。
如何选择将我的文件保存到哪个存储桶并从中读取?
这在 gridfs-stream 或其使用的底层本机 mongodb 驱动程序中没有详细记录,但您可以这样做:
这里是options
来自 gridfs-stream 的对象createWriteStream
example https://github.com/aheckmann/gridfs-stream#createwritestream(注意root
选项):
{
_id: '50e03d29edfdc00d34000001',
filename: 'my_file.txt',
mode: 'w',
chunkSize: 1024,
content_type: 'plain/text',
root: 'my_collection', // Bucket will be 'my_collection' instead of 'fs'
metadata: {
...
}
}
为什么它有效:
gridfs-stream 通过options
您传递调用的对象createWriteStream
or createReadStream
到底层 mongodb 驱动程序来创建gridStore
代表文件的对象。 mongodb驱动依次认识到root in the options object https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/gridfs/gridstore.js#L34作为默认“fs”网格存储桶前缀字符串的覆盖。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)