上传后,使用ExpressJS将文件存储在Mongo的GridFS中 [英] Store file in Mongo's GridFS with ExpressJS after upload
问题描述
我已经开始使用expressJS构建REST api.我是Node的新手,请耐心等待.我希望能够让用户使用/upload路由中的帖子直接将文件上传到Mongo的GridFS.
I have started building a REST api using expressJS. I am new to node so please bear with me. I want to be able to let users upload a file directly to Mongo's GridFS using a post to the /upload route.
据我在expressJS文档中所了解的,req.files.image对象在上传后的路径中可用,其中还包括路径和文件名属性.但是,如何准确读取图像数据并将其存储到GridFS中呢?
From what I understand in expressJS documentation the req.files.image object is available in the route after uploading, which also includes a path and filename attribute. But how can I exactly read the image data and store it into GridFS?
我已经研究了 gridfs-stream ,但我无法将两端结合在一起.我是否首先需要读取文件,然后将该数据用于writestream管道?还是可以只使用express中的文件对象,然后使用这些属性来构造一个writestream?任何指针将不胜感激!
I have looked into gridfs-stream but I can't tie ends together. Do I first need to read the file and then use that data for the writestream pipe? Or can I just use the file object from express and use those attributes to construct a writestream? Any pointers would be appreciated!
推荐答案
这是一个简单的演示:
Here's a simple demo:
var express = require('express');
var fs = require('fs');
var mongo = require('mongodb');
var Grid = require('gridfs-stream');
var db = new mongo.Db('test', new mongo.Server("127.0.0.1", 27017), { safe : false });
db.open(function (err) {
if (err) {
throw err;
}
var gfs = Grid(db, mongo);
var app = express();
app.use(express.bodyParser());
app.post('/upload', function(req, res) {
var tempfile = req.files.filename.path;
var origname = req.files.filename.name;
var writestream = gfs.createWriteStream({ filename: origname });
// open a stream to the temporary file created by Express...
fs.createReadStream(tempfile)
.on('end', function() {
res.send('OK');
})
.on('error', function() {
res.send('ERR');
})
// and pipe it to gfs
.pipe(writestream);
});
app.get('/download', function(req, res) {
// TODO: set proper mime type + filename, handle errors, etc...
gfs
// create a read stream from gfs...
.createReadStream({ filename: req.param('filename') })
// and pipe it to Express' response
.pipe(res);
});
app.listen(3012);
});
我使用 httpie 上传文件:
http --form post localhost:3012/upload filename@~/Desktop/test.png
您可以检查数据库是否上传了文件
You can check your database if the file is uploaded:
$ mongofiles list -d test
connected to: 127.0.0.1
test.png 5520
您也可以再次下载:
http --download get localhost:3012/download?filename=test.png
这篇关于上传后,使用ExpressJS将文件存储在Mongo的GridFS中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!