我正在开发一个以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());
答案 0 :(得分:87)
以下示例显示如何保存文件并从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);
}
}
}
<强>结果:强>
文件:
Chunks collection:
希望得到这个帮助。
答案 1 :(得分:18)
此示例允许您将文档绑定到对象
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; }
}