2

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

网络服务器.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);

服务.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 中。任何帮助表示赞赏。

4

1 回答 1

2

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

要更改这一点,您必须添加:

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

到 gridfs-stream 选项。

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

有关更多信息,请参见https://www.npmjs.org/package/gridfs-stream

于 2014-04-01T10:25:42.667 回答