MongoDB GridFs with C#,如何存储图像等文件? [英] MongoDB GridFs with C#, how to store files such as images?

查看:24
本文介绍了MongoDB GridFs with C#,如何存储图像等文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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());

推荐答案

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

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);
       } 
    }
 }

结果:

文件:

块集合:

希望对您有所帮助.

这篇关于MongoDB GridFs with C#,如何存储图像等文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆