67

我正在开发一个以 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());
4

3 回答 3

93

以下示例显示了如何保存文件并从 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);
       } 
    }
 }

结果:

文件:

文件 im mongodb

块集合:

块集合

希望这有帮助。

于 2011-02-14T09:26:24.627 回答
20

既然 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# 驱动程序测试的差异

于 2015-09-19T19:38:07.080 回答
19

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

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; }
}
于 2012-05-18T02:00:10.623 回答