I'm uploading image to server with following code:
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");
}
and trying to get file like:
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);
}
After upload I can see file in database, but when I'm trying to load it as
Context.Database.GridFS.FindOneById(new ObjectId(id));
I'm always geting null. Could you please suggest what I'm doing wrong?
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
It turned out I incorrectly searched for file by Id.
Instead of
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
I should use
var image = Context.Database.GridFS.FindOneById(id);
I used code from examples for previous version of driver but in 2.5 we don't need to use
new ObjectId(id)