使用 NoRM 驱动程序从 MongoDB 读取文件内容
我正在尝试读取存储在 MongoDB 中的图像文件,为此我在 ASP.net MVC 3 项目中有以下代码
public FileContentResult ProfileImage(ObjectId id)
{
using (var db = new MongoSession<User>())
{
var user = db.Queryable.Where(p => p.Id == id).FirstOrDefault();
if (user != null && user.ProfilePicture != null)
{
return File(user.ProfilePicture.Content.ToArray(), user.ProfilePicture.ContentType);
}
return null;
}
}
当查询数据库时,我可以看到 ProfilePicture
文件存在内容,但在 C# 项目中,内容长度为 0
。代码有什么问题吗?
I'm trying to read the image file stored in a MongoDB, to do that I have following code in my ASP.net MVC 3 projects
public FileContentResult ProfileImage(ObjectId id)
{
using (var db = new MongoSession<User>())
{
var user = db.Queryable.Where(p => p.Id == id).FirstOrDefault();
if (user != null && user.ProfilePicture != null)
{
return File(user.ProfilePicture.Content.ToArray(), user.ProfilePicture.ContentType);
}
return null;
}
}
When queried the database I can see the content exist for the ProfilePicture
file, but when here in the C# project the content length is 0
. Is there anything wrong in the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来好像您在
User
中嵌入了GridFile
,像That 这样的东西是行不通的;至少,不是通过默认行为。
GridFile
必须被视为一等公民,并且必须使用GridFileCollection
对象存储和检索它们:您可以在 NoRM 的单元测试。
原因是,虽然
GridFile
基本上是一个与其他类一样的类,但网格文件的存储方案非常不同。虽然“普通”对象是就地序列化的,并且一个文档始终对应于一个对象,但对于 GridFile 来说却并非如此。由于文件可能比 MongoDB 中的最大文档大小大得多,因此它们将被分成
块
。因此,当您存储GridFile
时,驱动程序将必须存储网格文件和许多块。默认情况下,块的大小为 256kB,因此块的数量将取决于数据大小。默认集合名称为fs.files
和fs.chunks
。所有这些逻辑都位于 GridFileCollection 类中,因此如果您只是存储嵌入的 GridFile 对象而不是调用 Files() ,则不会执行该逻辑 扩展显式检索
GridFileCollection
。It looks as if you were embedding
GridFile
inUser
, something likeThat won't work; at least, not through default behavior.
GridFile
s must be treated as first-class citizens, and they must be stored and retrieved using aGridFileCollection
object:You can find more working sample code in NoRM's unit tests.
The reason is that, while
GridFile
is basically a class like any other, the storage scheme for grid files is very different. While 'normal' objects are serialized in-place, and one document always corresponds to one object, this is not true forGridFile
.Because files can be much larger than the maximum document size in MongoDB, they'll be split up into
chunks
. Thus, when you store aGridFile
, the driver will have to store the grid file and a number of chunks. By default, chunks are 256kB in size, so the number of chunks will depend on the data size. The default collection names arefs.files
andfs.chunks
.All this logic resides in the
GridFileCollection
class, so it won't be executed if you're simply storing an embeddedGridFile
object instead of calling theFiles()
extension explicitly to retrieve theGridFileCollection
.