我需要将一些文件,如:图像、视频、pdf ......保存到 mongodb 中,所以我使用 gridfs-stream 和 express.js
var file = req.files.file;
req.pipe(gfs.createWriteStream({
filename:file.originalname,
mode:"w",
chunkSize:1024*4,
content_type:file.mimetype,
root:"fs"
})
res.send(200);
为了测试,我使用邮递员并以这种方式设置 POST 请求:
POST /fs/upload HTTP/1.1
Host: localhost:5000
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="epic.png"
Content-Type: image/png
----WebKitFormBoundaryE19zNvXGzXaLvS5C
问题是这种方式只存储文件的数据:
{
"_id" : ObjectId("54d14ec5b102fe401519a3c1"),
"filename" : "epic.png",
"contentType" : "image/png",
"length" : 0,
"chunkSize" : 4096,
"uploadDate" : ISODate("2015-02-03T22:42:14.730Z"),
"aliases" : null,
"metadata" : null,
"md5" : "993fb9ce262a96a81c79a38106147e95"
}
但不是我的意思是二进制数据的内容,mongodb存储它的属性长度等于0,因为fs.chucks中没有任何块。