1

I would like to upload an image using Asp.net core and MongoDb; however, I am not able to find the property GridFS in MongoDatabase class . I have checked the Google and did not have any luck.

The method in which I need to change GridFS to something else:

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

Does anyone know the correct way to upload a file in MongoDB using ASP.net Core?

1 Answer 1

1
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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.