Exemple #1
0
        public async Task <StoredFileInfo> StoreAsync(IFormFile file, CancellationToken cancellationToken = default)
        {
            _ = file ?? throw new ArgumentNullException(nameof(file));

            var           fileId = Guid.NewGuid().ToString();
            IGridFSBucket bucket = getBucket(_dbClient);

            StoredFileInfo fileInfo = await uploadFile(fileId, file, bucket, cancellationToken);

            return(fileInfo);
        }
Exemple #2
0
        private async Task <StoredFileInfo> uploadFile(string fileId, IFormFile file, IGridFSBucket bucket, CancellationToken cancellationToken = default)
        {
            var fileInfo = new StoredFileInfo
            {
                FileId      = fileId,
                FileName    = file.FileName,
                ContentType = file.ContentType,
                Length      = file.Length
            };

            using Stream fileStream = file.OpenReadStream();
            var uploadOptions = new GridFSUploadOptions
            {
                Metadata = BsonDocument.Parse(JsonSerializer.Serialize(fileInfo)),
            };

            // assigning filename in gridfs to fileid(for filtering by FileName while downloading file)
            _ = await bucket.UploadFromStreamAsync(fileId, fileStream, uploadOptions, cancellationToken);

            return(fileInfo);
        }