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

Javascript 使用gridFS在mongoDB中存储文件(图像),javascript,angularjs,mongodb,gridfs,gridfs-stream,Javascript,Angularjs,Mongodb,Gridfs,Gridfs Stream,我正在用angularJS编写这个网页,我希望人们在这里编辑和存储文本和图像。我已经创建了一个文件上传功能,可以让你从用户的电脑上传文件。问题是如何将此文件存储到mongoDB中。我已经阅读了很多关于gridFS的例子,但是没有一个与我的尝试相匹配。 这是我的密码: web-server.js: app.post('/uploadFile', function(req,res){ console.log("Retrieved:"); console.log(req.files); var Gr

我正在用angularJS编写这个网页,我希望人们在这里编辑和存储文本和图像。我已经创建了一个文件上传功能,可以让你从用户的电脑上传文件。问题是如何将此文件存储到mongoDB中。我已经阅读了很多关于gridFS的例子,但是没有一个与我的尝试相匹配。 这是我的密码:

web-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中存储的图像也没有。感谢您的帮助。

GridFS stream通常将其数据存储在db.fs.files/db.fs.chunks中(如果用户未设置)

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

{
   ....
   root: 'my_collection'
   ....
}
到gridfs流选项

来自NPM文档:

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: {
        ...
    }
} 

更多信息请参见。

我也在想同样的事情。回答此问题的人将得到+1