2015-02-06 102 views
0

我需要保存一些文件,如:圖片,視頻,PDF ......到M​​ongoDB的,所以我使用GridFS的流和express.js存儲的文件直接與GridFS的流的mongodb

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" 
} 

但不是我的意思de它的二進制數據的內容,進入mongodb是它存儲它的長度等於0,因爲沒有在fs.chucks任何塊。

回答

2

閱讀博客中找到了答案,用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); 
}); 
+0

難道這對你真的很有用,因爲它不適合我。該文件從未放在Gridfs中,儘管我得到一個錯誤,end()不是函數。 – 2015-03-23 11:05:36

+0

Btw:如果我刪除「this.upload.end()」周圍的「drain」事件函數,您的示例現在可以工作。如果我這樣實施它,有什麼問題嗎? – 2015-03-23 11:34:07

+0

好的一點我不確定如果中間件Mulder takecare somethig像排水事件時解析文件可能與屬性[inMemory](https://github.com/expressjs/multer#inmemory),應該工作,如果multer使用管道或一些在colud中使用其他使用管道的中間件類似 – Maxtermax 2015-05-11 02:18:57