这是我将文件上传和下载到 GridFS 的 express.js 代码:
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 构造函数的示例,但正如您所见,我在这里没有这样做。该文档还说可以提供不同的存储桶名称,但我没有看到任何有关如何的信息。
如何选择将我的文件保存到哪个存储桶并从中读取?