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

Using gridFS to store files(images) in mongoDB

本文关键字:图像 存储文件 gridFS mongoDB 使用      更新时间:2023-09-26

我正在用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中的图像也没有。任何帮助,不胜感激。

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

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

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

到网格流选项。

来自 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。