2015-06-21 57 views
1

我使用mongoskin在我的项目中连接mongodb。现在我有要求使用GridF上传图像,音频等。我有一个HTML表单来上传这些文件。使用GridFS使用mongoskin上传文件的示例代码

我试图找出使用mongoskin上传文件的示例代码,但找不到任何好的代码。

请帮忙。

回答

0

花了很多小时后,我可以使用mongoskin将文件上传到Gridfs。不知道这是完美的代码共享但是在这里,因为我无法在谷歌搜索:-)

https://github.com/dilipkumar2k6/gridfs-mongoskin 


var DBModule = require('./DBModule.js'); 
var Grid = require('gridfs-stream'); 
var mongoskin = require('mongoskin'); 

//Upload file to server and also update the database 
exports.uploadContent = function (req, res) { 
    console.log('Calling uploadFile inside FileUploadService'); 
    req.pipe(req.busboy); 
    req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { 
     console.log('uploadFile after busboy fieldname: ' + fieldname + ", file : " + file + ", filename : " + filename); 
     // make sure the db instance is open before passing into `Grid` 
     var gfs = Grid(DBModule.db, mongoskin); 
     //Get metadata var host = req.headers['host']; 
     var metadata = {contentType: mimetype}; 
     var writestream = gfs.createWriteStream({filename: filename, metadata: metadata}); 
     file.pipe(writestream); 
     writestream.on('close', function (file) { 
      // return URL to acces the uploaded content 
      var path = "contents/" + file._id; 
      res.json({"path": path}); 
     }); 

     writestream.on('error', function (err) { 
      log.error({err: err}, 'Failed to upload file to database'); 
      res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR); 
      res.json({error: err}); 
     }); 
    }); 
}; 
//view file from database 
exports.previewContent = function (req, res) { 
    var contentId = new DBModule.BSON.ObjectID(req.params.contentid); 
    console.log('Calling previewFile inside FileUploadService for content id ' + contentId); 

    var gs = DBModule.db.gridStore(contentId, 'r'); 
    gs.read(function (err, data) { 
     if (!err) { 
      //res.setHeader('Content-Type', metadata.contentType); 
      res.end(data); 
     } else { 
      log.error({err: err}, 'Failed to read the content for id ' + contentId); 
      res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR); 
      res.json({error: err}); 
     } 
    }); 
}; 
0

试试这个存储使用GridFS的数据(默认使用mongoskin)找到任何一个工作代码。它为我工作。

var ObjectID = require('mongodb').ObjectID, 
    GridStore = require('mongodb').GridStore; 
    exports.saveMedia = function(db, media, next) { 
     console.log(media) 
     db.open(function (err, db) { 
      // Create a file and open it 
      var gridStore = new GridStore(db, new ObjectID(), "w"); 
      gridStore.open(function (err, gridStore) { 
       // Write some content to the file 
       gridStore.write(new Buffer(media), function (err, gridStore) { 
        // Flush the file to db 
        gridStore.close(function (err, fileData) 
         //returns filename 
         next(null, fileData) 
        }); 
       }); 
      }); 
     }); 
    }