代码之家  ›  专栏  ›  技术社区  ›  Alex Kapelyukhovskiy

MongoDb。GridFS。FindOneById返回null

  •  0
  • Alex Kapelyukhovskiy  · 技术社区  · 6 年前

    我正在使用以下代码将图像上载到服务器:

    public ActionResult AttachImage(HttpPostedFileBase file)
    {
       var options = new MongoGridFSCreateOptions
       {
          Id = ObjectId.GenerateNewId().ToString(),
          ContentType = file.ContentType
        };
        Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
        return RedirectToAction("Index");
    }
    

    并尝试获取如下文件:

    public ActionResult GetImage(string id)
    {
       var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
       if(image == null)
       {
          return HttpNotFound();
       }
       return File(image.OpenRead(), image.ContentType);
    }
    

    上传后,我可以在数据库中看到文件,但当我尝试将其加载为

    Context.Database.GridFS.FindOneById(new ObjectId(id));
    

    我总是得到空值。你能告诉我我做错了什么吗?

    public class DbContext
    {
        public MongoDatabase Database;
        public DbContext()
        {
            var client = new MongoClient(Properties.Settings.Default.ConnectionString);
            var server = client.GetServer();
            Database = server.GetDatabase(Properties.Settings.Default.DatabaseName);
        }
    }
    

    mongocsharpdriver 2.5.0 mongo server 3.6

    1 回复  |  直到 6 年前
        1
  •  0
  •   Alex Kapelyukhovskiy    6 年前

    结果是我按Id错误地搜索了文件。

    而不是

    var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
    

    我应该使用

    var image = Context.Database.GridFS.FindOneById(id);
    

    我使用了先前版本驱动程序示例中的代码,但在2.5中,我们不需要使用

     new ObjectId(id)