我想使用Asp.net核心和MongoDb上传图片;但是,我无法在GridFS
课程中找到属性MongoDatabase
。我检查了谷歌并没有任何运气。
我需要将GridFS
更改为其他内容的方法:
private async Task StoreImage(Computer computer, IFormFile file)
{
var imageId = ObjectId.GenerateNewId();
computer.ImageId = imageId.ToString();
var filter = Builders<Computer>.Filter.Eq("_id", new ObjectId(computer.Id));
var update = Builders<Computer>.Update.Set("ImageId", computer.ImageId);
await db.Computers.UpdateOneAsync(filter, update);
db.GridFS.Upload(file.ToBson(), file.FileName, new MongoGridFSCreateOptions
{
Id = imageId,
ContentType = file.ContentType
});
}
有没有人知道使用ASP.net Core在MongoDB中上传文件的正确方法?
答案 0 :(得分:0)
public class CdnDbContext
{
public IGridFSBucket GridFsBucket { get; set; }
public CdnDbContext()
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = config.GetConnectionString("MongoCdn");
var connection = new MongoUrl(connectionString);
var settings = MongoClientSettings.FromUrl(connection);
var client = new MongoClient(settings);
var database = client.GetDatabase(connection.DatabaseName);
GridFsBucket = new GridFSBucket(database);
}
}