簡體   English   中英

使用gridfs-stream將文件直接存儲在mongodb中

[英]stored files directly in mongodb with gridfs-stream

我需要保存一些文件,例如:images,video,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中沒有任何塊。

通過在博客中閱讀,發現了使用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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM