使用gridFS在mongoDB中存储文件(图像)

时间:2014-04-01 09:03:47

标签: javascript angularjs mongodb gridfs gridfs-stream

我正在angularJS中编写此网页,我希望人们编辑和存储文本和图像。我创建了一个文件上传功能,让你从用户计算机上传文件。问题是将此文件存储到mongoDB中。我在gridFS上阅读了很多例子,但没有一个与我想要做的完全匹配。 这是我的代码:

网络server.js:

app.post('/uploadFile', function(req,res){
console.log("Retrieved:");
console.log(req.files);

var Grid = require('gridfs-stream');
var gfs = Grid(DB, mongoose.mongo);
// streaming to gridfs
var writestream = gfs.createWriteStream(req.files.file);    
fs.createReadStream(req.files.file.path).pipe(writestream);

services.js:

function uploadFilesToServer(file){ 
    var fd = new FormData();
    fd.append("file", file);
    var deferred = $q.defer();
    console.log("trying to save:");
    console.log(file);
    $http({
        method:"POST",
        url: "uploadFile",
        data: fd,
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success(function(data){
        var returnValue = [true, file, data];
        deferred.resolve(returnValue);
    }).error(function(data){
        var returnValue = [false, file, data];
        deferred.resolve(returnValue);
    });
    return deferred.promise;
}

目前,当我运行代码时,我没有收到任何错误消息,但是这些图像都不存储在db.files或db.chunks中。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

如果没有用户设置,GridFS流通常会将其数据存储在db.fs.files / db.fs.chunks中。

要更改此设置,您必须添加:

{
   ....
   root: 'my_collection'
   ....
}

到gridfs-stream选项。

来自NPM docs:

createWriteStream

To stream data to GridFS we call createWriteStream passing any options.

var writestream = gfs.createWriteStream([options]);
fs.createReadStream('/some/path').pipe(writestream);
Options may contain zero or more of the following options...

{
    _id: '50e03d29edfdc00d34000001', // a MongoDb ObjectId
    filename: 'my_file.txt', // a filename
    mode: 'w', // default value: w+, possible options: w, w+ or r, 
    see [GridStore]    
    (http://mongodb.github.com/node-mongodb-native/api-generated/gridstore.html)

    //any other options from the GridStore may be passed too, e.g.:

    chunkSize: 1024, 
    content_type: 'plain/text', 
    // For content_type to work properly, set "mode"-option to "w" too!
    root: 'my_collection',
    metadata: {
        ...
    }
} 

有关详情,请参阅https://www.npmjs.org/package/gridfs-stream