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

标签 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 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 中。如有任何帮助,我们将不胜感激。

最佳答案

如果用户未设置,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了解更多。

关于javascript - 使用gridFS在mongoDB中存储文件(图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22781267/

相关文章:

java - 我可以使用 fastxml 将日期写入 ISODate 以使用即将到期的 mongodb 索引吗?

javascript - 不一致的 Javascript 排序

javascript - 在 CSS 中按半像素移动的图像插值

javascript - 数据表排序不正确

arrays - 使用angular js根据第一个选择的选项过滤第二个选择框

node.js - 插入记录而不会因重复而失败

javascript - Extjs 仅将单元格文本向右对齐

javascript - 在 AngularJS 中使用带有下划线的 WordPress Post Meta 时出现未定义

angularjs - 当关闭 Bootstrap 模型区域之外的模态时触发事件处理程序

MongoDB 如何使用 $date 运算符进行查询?