【问题标题】:stored files directly in mongodb with gridfs-stream使用 gridfs-stream 将文件直接存储在 mongodb 中
【发布时间】:2015-04-06 02:26:49
【问题描述】:

我需要将一些文件,例如:图像、视频、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 中没有任何块。

【问题讨论】:

    标签: node.js mongodb file gridfs-stream


    【解决方案1】:

    在博客中阅读找到了使用 express.js、gridfs-stream.js 和 multer 中间件直接在数据库中流式传输数据的答案:

    var multer = require('multer');
    
    app.post('/fs/upload', multer({
        upload: null,// take uploading process 
    
        onFileUploadStart: function (file) {
            //set upload with WritableStream        
            this.upload = gfs.createWriteStream({
                filename: file.originalname,
                mode: "w",
                chunkSize: 1024*4,
                content_type: file.mimetype,
                root: "fs"
            });
         },
    
         onFileUploadData: function (file, data) {
            //put the chucks into db 
            this.upload.write(data);
         },
    
         onFileUploadComplete: function (file) {
            //end process 
            this.upload.on('drain', function () {
                this.upload.end();
            });
         }
    }), function (req, res) {
       res.sendStatus(200);
    });
    

    为了测试这个:

    app.route('/fs/download/:file').get(function (req, res) {
       var readstream = gfs.createReadStream({_id: req.params.file});
       readstream.pipe(res);
    });
    

    【讨论】:

    • 这对你真的有用吗,因为它不适合我。该文件从未放在 Gridfs 中,虽然我遇到了一个错误,但 end() 不是一个函数。
    • 顺便说一句:如果我删除“this.upload.end()”周围的“drain”事件函数,您的示例现在有效。如果我这样实现有什么问题吗?
    • 好点我不确定中间件 multer 在解析文件时是否会处理类似排水事件之类的问题使用管道
    猜你喜欢
    • 1970-01-01
    • 2015-09-23
    • 2014-05-11
    • 2013-10-27
    • 2016-07-06
    • 2016-04-05
    • 2015-07-18
    • 2012-11-17
    • 1970-01-01
    相关资源
    最近更新 更多