MongoDB GridFs用C#,如何存储图像等文件?

发布于 2024-10-17 01:13:13 字数 482 浏览 5 评论 0原文

我正在开发一个以 mongodb 作为后端的网络应用程序。我想让用户将图片上传到他们的个人资料中,例如链接的个人资料图片。我正在使用带有 MVC2 的 aspx 页面,并且我读到 GridFs 库用于将大型文件类型存储为二进制文件。我到处寻找如何完成此操作的线索,但 mongodb 没有任何 C# api 或 GridFs C# 的文档。我感到困惑和困惑,真的可以使用另一组大脑。

有人知道如何实际实现一个文件上传控制器,将用户上传的图像存储到 mongodb 集合中吗?谢谢一百万!

我尝试过这种方法的变体,但没有成功。

Database db = mongo.getDB("Blog");
GridFile file = new GridFile(db);
file.Create("image.jpg");

var images = db.GetCollection("images");
images.Insert(file.ToDocument());

I'm developing a web app with mongodb as my back-end. I'd like to have users upload pictures to their profiles like a linked-in profile pic. I'm using an aspx page with MVC2 and I read that GridFs library is used to store large file types as binaries. I've looked everywhere for clues as how this is done, but mongodb doesn't have any documentation for C# api or GridFs C#. I'm baffled and confused, could really use another set of brains.

Anyone one know how to actually implement a file upload controller that stores an image uploaded by a user into a mongodb collection? Thanks a million!

I've tried variations of this to no avail.

Database db = mongo.getDB("Blog");
GridFile file = new GridFile(db);
file.Create("image.jpg");

var images = db.GetCollection("images");
images.Insert(file.ToDocument());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

偏爱自由 2024-10-24 01:13:14

既然 2.1 RC-0 驱动程序已经发布,上述答案很快就会过时。

现在可以通过以下方式使用 GridFS 处理 v2.1 MongoDB 中的文件:

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System.IO;
using System.Threading.Tasks;

namespace MongoGridFSTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new MongoClient("mongodb://localhost");
            var database = client.GetDatabase("TestDB");
            var fs = new GridFSBucket(database);

            var id = UploadFile(fs);

            DownloadFile(fs, id);
        }

        private static ObjectId UploadFile(GridFSBucket fs)
        {
            using (var s = File.OpenRead(@"c:\temp\test.txt"))
            {
                var t = Task.Run<ObjectId>(() => { return 
                    fs.UploadFromStreamAsync("test.txt", s);
                });

                return t.Result;
            }
        }

        private static void DownloadFile(GridFSBucket fs, ObjectId id)
        {
            //This works
            var t = fs.DownloadAsBytesByNameAsync("test.txt");
            Task.WaitAll(t);
            var bytes = t.Result;


            //This blows chunks (I think it's a driver bug, I'm using 2.1 RC-0)
            var x = fs.DownloadAsBytesAsync(id);
            Task.WaitAll(x);
        }
    }
}

这取自 C# 驱动程序测试的差异 此处

The answers above are soon to be outdated now that the 2.1 RC-0 driver has been released.

The way to work with files in v2.1 MongoDB with GridFS can now be done this way:

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System.IO;
using System.Threading.Tasks;

namespace MongoGridFSTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new MongoClient("mongodb://localhost");
            var database = client.GetDatabase("TestDB");
            var fs = new GridFSBucket(database);

            var id = UploadFile(fs);

            DownloadFile(fs, id);
        }

        private static ObjectId UploadFile(GridFSBucket fs)
        {
            using (var s = File.OpenRead(@"c:\temp\test.txt"))
            {
                var t = Task.Run<ObjectId>(() => { return 
                    fs.UploadFromStreamAsync("test.txt", s);
                });

                return t.Result;
            }
        }

        private static void DownloadFile(GridFSBucket fs, ObjectId id)
        {
            //This works
            var t = fs.DownloadAsBytesByNameAsync("test.txt");
            Task.WaitAll(t);
            var bytes = t.Result;


            //This blows chunks (I think it's a driver bug, I'm using 2.1 RC-0)
            var x = fs.DownloadAsBytesAsync(id);
            Task.WaitAll(x);
        }
    }
}

This is taken from a diff on the C# driver tests here

北座城市 2024-10-24 01:13:14

此示例将允许您将文档绑定到对象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        MongoServer ms = MongoServer.Create();
        string _dbName = "docs";

        MongoDatabase md = ms.GetDatabase(_dbName);
        if (!md.CollectionExists(_dbName))
        {
            md.CreateCollection(_dbName);
        }

        MongoCollection<Doc> _documents = md.GetCollection<Doc>(_dbName);
        _documents.RemoveAll();
        //add file to GridFS

        MongoGridFS gfs = new MongoGridFS(md);
        MongoGridFSFileInfo gfsi = gfs.Upload(@"c:\mongodb.rtf");
        _documents.Insert(new Doc()
        {
            DocId = gfsi.Id.AsObjectId,
            DocName = @"c:\foo.rtf"
        }
        );

        foreach (Doc item in _documents.FindAll())
        {
            ObjectId _documentid = new ObjectId(item.DocId.ToString());
            MongoGridFSFileInfo _fileInfo = md.GridFS.FindOne(Query.EQ("_id", _documentid));
            gfs.Download(item.DocName, _fileInfo);
            Console.WriteLine("Downloaded {0}", item.DocName);
            Console.WriteLine("DocName {0} dowloaded", item.DocName);
        }

        Console.ReadKey();
    }
}

class Doc
{
    public ObjectId Id { get; set; }
    public string DocName { get; set; }
    public ObjectId DocId { get; set; }
}

This example will allow you to tie a document to an object

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using System.IO;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        MongoServer ms = MongoServer.Create();
        string _dbName = "docs";

        MongoDatabase md = ms.GetDatabase(_dbName);
        if (!md.CollectionExists(_dbName))
        {
            md.CreateCollection(_dbName);
        }

        MongoCollection<Doc> _documents = md.GetCollection<Doc>(_dbName);
        _documents.RemoveAll();
        //add file to GridFS

        MongoGridFS gfs = new MongoGridFS(md);
        MongoGridFSFileInfo gfsi = gfs.Upload(@"c:\mongodb.rtf");
        _documents.Insert(new Doc()
        {
            DocId = gfsi.Id.AsObjectId,
            DocName = @"c:\foo.rtf"
        }
        );

        foreach (Doc item in _documents.FindAll())
        {
            ObjectId _documentid = new ObjectId(item.DocId.ToString());
            MongoGridFSFileInfo _fileInfo = md.GridFS.FindOne(Query.EQ("_id", _documentid));
            gfs.Download(item.DocName, _fileInfo);
            Console.WriteLine("Downloaded {0}", item.DocName);
            Console.WriteLine("DocName {0} dowloaded", item.DocName);
        }

        Console.ReadKey();
    }
}

class Doc
{
    public ObjectId Id { get; set; }
    public string DocName { get; set; }
    public ObjectId DocId { get; set; }
}
别再吹冷风 2024-10-24 01:13:13

以下示例展示如何保存文件并从 gridfs 读回(使用官方 mongodb 驱动程序):

 var server = MongoServer.Create("mongodb://localhost:27020");
 var database = server.GetDatabase("tesdb");

 var fileName = "D:\\Untitled.png";
 var newFileName = "D:\\new_Untitled.png";
 using (var fs = new FileStream(fileName, FileMode.Open))
 {
    var gridFsInfo = database.GridFS.Upload(fs, fileName);
    var fileId = gridFsInfo.Id;

    ObjectId oid= new ObjectId(fileId);
    var file = database.GridFS.FindOne(Query.EQ("_id", oid));

    using (var stream = file.OpenRead())
    {
       var bytes = new byte[stream.Length];
       stream.Read(bytes, 0, (int)stream.Length);
       using(var newFs = new FileStream(newFileName, FileMode.Create))
       {
         newFs.Write(bytes, 0, bytes.Length);
       } 
    }
 }

结果:

文件:

File im mongodb

块集合:

Chunks collection

希望有所帮助。

Following example show how to save file and read back from gridfs(using official mongodb driver):

 var server = MongoServer.Create("mongodb://localhost:27020");
 var database = server.GetDatabase("tesdb");

 var fileName = "D:\\Untitled.png";
 var newFileName = "D:\\new_Untitled.png";
 using (var fs = new FileStream(fileName, FileMode.Open))
 {
    var gridFsInfo = database.GridFS.Upload(fs, fileName);
    var fileId = gridFsInfo.Id;

    ObjectId oid= new ObjectId(fileId);
    var file = database.GridFS.FindOne(Query.EQ("_id", oid));

    using (var stream = file.OpenRead())
    {
       var bytes = new byte[stream.Length];
       stream.Read(bytes, 0, (int)stream.Length);
       using(var newFs = new FileStream(newFileName, FileMode.Create))
       {
         newFs.Write(bytes, 0, bytes.Length);
       } 
    }
 }

Results:

File:

File im mongodb

Chunks collection:

Chunks collection

Hope this help.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文