MongoDB GridF与C#,如何存储图像等文件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (83)

我正在开发一个以mongodb作为后端的web应用程序。我希望让用户将图片上传到他们的个人资料中,例如链接的个人资料照片。我正在使用带有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());
提问于
用户回答回答于

下面的示例演示如何保存文件并从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:

Chunks collection:

用户回答回答于
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; }
}

扫码关注云+社区

领取腾讯云代金券