예제 #1
0
        /*
         * Edition stuff
         */
        public async Task <Challenge> CreateChallengeAsync(Challenge toCreate)
        {
            if (string.IsNullOrWhiteSpace(toCreate.Name))
            {
                throw new Exception("You must provide a name to the challenge");
            }
            if (string.IsNullOrWhiteSpace(toCreate.Description))
            {
                throw new Exception("You must provide a description to the challenge");
            }

            // If we don't do this, it try to convert it to object id
            toCreate.ImageId = null;

            await _challenges.InsertOneAsync(toCreate);

            var challengeImage = await _gridFS.UploadFromBytesAsync($"challenge_{toCreate.Id}", toCreate.Image);

            toCreate.Image   = null;
            toCreate.ImageId = challengeImage.ToString();

            await _challenges.ReplaceOneAsync(databaseChallenge => databaseChallenge.Id == toCreate.Id, toCreate);

            return(toCreate);
        }
예제 #2
0
 public async Task <ObjectId> UploadFile(string fileName, byte[] source, GridFSUploadOptions options, CancellationToken token = default(CancellationToken))
 {
     if (_bucket == null)
     {
         return(new ObjectId());
     }
     return(await _bucket.UploadFromBytesAsync(fileName, source, options, token));
 }
예제 #3
0
        public async Task <object> UpLoadFileAsync(string fileType, byte[] imageBytes)
        {
            //暂时采用guid来作为文件名,
            string fileName = $"{Guid.NewGuid().ToString()}.{fileType}";
            var    id       = await bucket.UploadFromBytesAsync(fileName, imageBytes);

            //暂时不知道返回Id如何保存金mysql数据库
            return(fileName);
        }
예제 #4
0
        public async Task <ObjectId> Save(byte[] data, string filename)
        {
            var(w, h) = _modificator.GetSize(data);
            var gridFsImageId = await _gridFs.UploadFromBytesAsync(filename, data);

            _logger.LogInformation($"Saved picture {filename} for {gridFsImageId}");

            var pictureEntity = PictureEntity.WithNoId(filename, h, w, new List <ObjectId> {
                gridFsImageId
            });
            await _pictures.InsertOneAsync(pictureEntity);

            return(pictureEntity.Id);
        }
        public static async Task <bool> uploadFileToGridFS(string filename)
        {
            var bucket = new GridFSBucket(_database, new GridFSBucketOptions
            {
                BucketName     = "excelSpreadsheets",
                ChunkSizeBytes = 1048576, // 1MB
                WriteConcern   = WriteConcern.W1,
                ReadPreference = ReadPreference.Primary
            }
                                          );

            try
            {
                byte[] source = System.IO.File.ReadAllBytes(filename);
                await bucket.UploadFromBytesAsync(filename, source);
            }
            catch (Exception e)
            {
                Logger.logMessage("Cannot establish connection to MongoDB. Exception: " + e.Message, Logger.LogLevel.ERROR);
                return(false);
            }


            return(true);
        }
예제 #6
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <string> UpLoadFile(MongoDbFileDoc doc, GridFSUploadOptions options = null)
        {
            var bucket = new GridFSBucket(GetMongoDatabase(), new GridFSBucketOptions());
            var id     = await bucket.UploadFromBytesAsync(doc.FileName, doc.FileBytes, options);

            return(id.ToString());
        }
예제 #7
0
        public bool SendDocuments(string FileName, byte[] FileBytes)
        {
            GridFSBucket GridFs   = new GridFSBucket(_db);
            var          ObjectId = GridFs.UploadFromBytesAsync(FileName, FileBytes);

            return(true);
        }
예제 #8
0
        private async Task <File> InsertFileContent(File file)
        {
            var fileId = await _bucket.UploadFromBytesAsync(file.FileName, file.FileContent);

            file.FileId = fileId.ToString();
            return(file);
        }
예제 #9
0
        /// <summary>
        /// GridFS文件操作——上传异步
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileData"></param>
        /// <returns></returns>
        async public Task <ObjectId> UpLoadAsync(string fileName, byte[] fileData)
        {
            var      gridfs = new GridFSBucket(database);
            ObjectId oId    = await gridfs.UploadFromBytesAsync(fileName, fileData);

            return(oId);
        }
예제 #10
0
        //************************************************************************ARCHIVOS***************************************************************************************
        //FALTA PROBARLO
        public bool SendDocument(string fileName, byte[] fileBytes)
        {
            GridFSBucket gfs      = new GridFSBucket(_db);
            var          objectId = gfs.UploadFromBytesAsync(fileName, fileBytes);

            return(true);
        }
예제 #11
0
        public async ValueTask <Score> Create(Score score)
        {
            var scoreTrack = Convert.FromBase64String(score.Track);

            try
            {
                var id = await _gridFsBucket.UploadFromBytesAsync(score.Title, scoreTrack, new GridFSUploadOptions
                {
                    Metadata = new BsonDocument
                    {
                        { "Composer", score.Composer }
                    }
                });

                score.Id = id.ToString();

                await _scores.InsertOneAsync(score);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);

                throw;
            }

            return(score);
        }
예제 #12
0
        public async Task <ObjectId> UploadFromBytesAsync(byte[] source, string fileName, GridFSUploadOptions options = null)
        {
            MongoClient client = GetClient(m_connectionStr);
            var         db     = client.GetDatabase(DatabaseName);
            var         bucket = new GridFSBucket(db, BucksOptions);

            return(await bucket.UploadFromBytesAsync(fileName, source, options));
        }
예제 #13
0
        public async Task <IActionResult> FS()
        {
            var    mongo       = new MongoDBTool().GetMongoDatabase();
            var    bucket      = new GridFSBucket(mongo);
            string newJsonPath = $@"{hostingEnvironment.ContentRootPath}/wwwroot/account/car_number_new.json";
            await bucket.UploadFromBytesAsync(Path.GetFileNameWithoutExtension(newJsonPath), System.IO.File.ReadAllBytes(newJsonPath));

            return(this.JsonSuccessStatus());
        }
예제 #14
0
        public async Task <string> UploadAsync(UploadModel uploadModel)
        {
            GridFSUploadOptions fsOption = new GridFSUploadOptions()
            {
                Metadata = new BsonDocument(nameof(uploadModel.CreateUserId), uploadModel.CreateUserId)
            };

            ObjectId objectId = await GridFSBucket.UploadFromBytesAsync(uploadModel.FileName, uploadModel.Source, fsOption);

            return(objectId.ToString());
        }
예제 #15
0
        public async Task <FileDetails> UploadFileFromBytesAsync(byte[] bytes, FileDetails fileDetails)
        {
            var id = await fsBucket.UploadFromBytesAsync(fileDetails.Name, bytes);

            fileDetails.Id = id.ToString();

            var collection = fileInfoDB.GetCollection <FileDetails>(fileInfoDbName);
            await collection.InsertOneAsync(fileDetails);

            return(fileDetails);
        }
예제 #16
0
        public string UploadFile(byte[] stream, string location, string date)
        {
            //IGridFSBucket bucket;
            var t = Task.Run <ObjectId>(() => {
                return
                (bucket.UploadFromBytesAsync(location + date + ".pdf", stream));
                //fs.UploadFromStreamAsync("test.pdf", stream);
            });

            return(t.Result.ToString());
        }
예제 #17
0
 public async virtual Task InsertChunkAsync(T document)
 {
     try
     {
         var bucket = new GridFSBucket(MongoDatabase);
         var res    = await bucket.UploadFromBytesAsync(document.Id.ToString(), document.Data);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
예제 #18
0
        /*
         * Edition stuff
         */
        public async Task UpdateUserAsync(User toUpdate)
        {
            if (string.IsNullOrWhiteSpace(toUpdate.Id))
            {
                throw new Exception("The id must be provided in the body");
            }

            // If we don't do it manally old images are never deleted
            var oldUser = await(await _users.FindAsync(databaseUser => databaseUser.Id == toUpdate.Id)).FirstOrDefaultAsync();

            if (oldUser == null)
            {
                throw new Exception("The user doesn't exist");
            }

            if (toUpdate.ProfilePictureId == "modified")
            {
                if (!string.IsNullOrWhiteSpace(oldUser.ProfilePictureId))
                {
                    await _gridFS.DeleteAsync(new ObjectId(oldUser.ProfilePictureId));
                }

                var userImage = await _gridFS.UploadFromBytesAsync($"user_{toUpdate.Id}", toUpdate.ProfilePicture);

                toUpdate.ProfilePicture   = null;
                toUpdate.ProfilePictureId = userImage.ToString();
            }
            else
            {
                toUpdate.ProfilePictureId = oldUser.ProfilePictureId;
            }

            toUpdate.WaitingCallenges  = oldUser.WaitingCallenges;
            toUpdate.FinishedCallenges = oldUser.FinishedCallenges;
            toUpdate.PasswordHash      = oldUser.PasswordHash;
            toUpdate.PasswordSalt      = oldUser.PasswordSalt;

            await _users.ReplaceOneAsync(databaseUser => databaseUser.Id == toUpdate.Id, toUpdate);
        }
예제 #19
0
        public async Task <IFileProperties> PostAsync(string fileName, byte[] content, string contentType)
        {
            var fs = new GridFSBucket(_context.Database);
            var id = await fs.UploadFromBytesAsync(fileName, content, new GridFSUploadOptions { Metadata = new BsonDocument("contentType", contentType) });

            if (id != null)
            {
                return(GetProperties(id.ToString()));
            }
            else
            {
                return(null);
            }
        }
예제 #20
0
        public async Task DropAsync_should_drop_the_files_and_chunks_collections()
        {
            var client   = DriverTestConfiguration.Client;
            var database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
            var subject  = new GridFSBucket(database);
            await subject.UploadFromBytesAsync("test", new byte[] { 0 }); // causes the collections to be created

            await subject.DropAsync();

            var collections     = await(await database.ListCollectionsAsync()).ToListAsync();
            var collectionNames = collections.Select(c => c["name"].AsString);

            collectionNames.Should().NotContain("fs.files");
            collectionNames.Should().NotContain("fs.chunks");
        }
예제 #21
0
        public async Task <string> UploadFile(string filename, byte[] fileBytes, bool shouldOverride = true)
        {
            if (shouldOverride)
            {
                var filter = Builders <GridFSFileInfo <ObjectId> > .Filter.Eq(x => x.Filename, filename);

                var currentFile = await(await _gridFS.FindAsync(filter)).FirstOrDefaultAsync();

                if (currentFile != null)
                {
                    await _gridFS.DeleteAsync(currentFile.Id);
                }
            }

            var file = await _gridFS.UploadFromBytesAsync(filename, fileBytes);

            return(file.ToString());
        }
예제 #22
0
        public async Task <ObjectId> UploadAsync(string filename, byte[] bytes)
        {
            var bucket = new GridFSBucket(Repository.Collection.Database); //这个是初始化gridFs存储的

            // 计算MD5;
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var           hash   = md5.ComputeHash(bytes);
            StringBuilder result = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                result.Append(hash[i].ToString("x2"));
            }
            var md5Str = result.ToString();
            // 处理重复文件;
            ObjectId fileId;
            var      fileList = bucket.Find(new { md5 = md5Str }.ToBsonDocument(), new GridFSFindOptions
            {
                Limit = 1
            }).ToList();

            if (fileList.Any())
            {
                var fInfo = fileList.First();
                fileId = fInfo.Id;
            }
            else
            {
                fileId = await bucket.UploadFromBytesAsync(filename, bytes, new GridFSUploadOptions
                {
                    DisableMD5 = false
                });
            }
            // 插入素材记录;
            var entity = new Material
            {
                FileId = fileId.ToString(),
                Name   = filename,
                MD5    = md5Str
            };

            Repository.Insert(entity);
            return(entity.ObjectId);
        }
예제 #23
0
        internal async Task <byte[]> GetQRPic(string uniacid, ObjectId accountID, string contentRootPath)
        {
            var account = GetModelByIDAndUniacID(accountID, uniacid);

            if (string.IsNullOrEmpty(account.AccountPhoneNumber) || string.IsNullOrEmpty(account.CarNumber))
            {
                string no_qrPath = $@"{contentRootPath}/wwwroot/images/no_qr.jpg";
                return(File.ReadAllBytes(no_qrPath));
            }
            byte[] qrData;
            var    bucket = new GridFSBucket(mongoDB);

            if (account.QRFileID != ObjectId.Empty)
            {
                return(await bucket.DownloadAsBytesAsync(account.QRFileID));
            }
            string       qrInfo = $@"{We7Config.SiteRoot}account/GetAccountInfo?uniacid={uniacid}&AccountID={account.AccountID}";
            Bitmap       qr     = QRCodeHelper.Create(qrInfo, 300);
            Image        qrRaw  = ImageTools.ResizeImage(qr, 286, 286, 0);
            string       bgPath = $@"{contentRootPath}/wwwroot/images/qr_bg.jpg";
            Bitmap       qrBit  = ImageTools.CombinImage(new Bitmap(bgPath), qrRaw, 171, 128);
            MemoryStream ms     = new MemoryStream();

            qrBit.Save(ms, ImageFormat.Jpeg);
            qrData = ms.GetBuffer();
            var options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument {
                    { "content-type", "Image/jpg" }
                }
            };
            var id = await bucket.UploadFromBytesAsync($"qr_{accountID.ToString()}.jpg", qrData, options);

            collection.UpdateOne(x => x.AccountID.Equals(accountID) && x.uniacid.Equals(uniacid), Builders <AccountModel> .Update.Set(x => x.QRFileID, id));
            return(qrData);
        }
예제 #24
0
        public async Task <string> UploadFile(string fileName, byte[] buffer)
        {
            try
            {
                string hash = GetMD5Hash(buffer);

                var file = await GetFileByMD5(hash);

                if (file != null) //file already exists in the database, so no need to upload it again, just return its Id
                {
                    return(file.Id.ToString());
                }
                else //this is a new file, upload it in the database
                {
                    var id = await gridFs.UploadFromBytesAsync(fileName, buffer);

                    return(id.ToString());
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
 private async Task <ObjectId> SeedBucket(byte[] seed)
 {
     return(await _bucket.UploadFromBytesAsync(Path.GetRandomFileName(), seed));
 }
예제 #26
0
        /// <summary>
        /// 上传文件
        /// </summary>
        public async Task <ObjectId> UploadFileAsync(string fileName, byte[] source)
        {
            var id = await _bucket.UploadFromBytesAsync(fileName, source);

            return(id);
        }
예제 #27
0
 public async Task <string> CreateAsync(IPrincipal user, FileModel item)
 {
     return((await _bucket.UploadFromBytesAsync(item.Name, item.Contents)).ToString());
 }
        public async Task DropAsync_should_drop_the_files_and_chunks_collections()
        {
            var client = DriverTestConfiguration.Client;
            var database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
            var subject = new GridFSBucket(database);
            await subject.UploadFromBytesAsync("test", new byte[] { 0 }); // causes the collections to be created

            await subject.DropAsync();

            var collections = await (await database.ListCollectionsAsync()).ToListAsync();
            var collectionNames = collections.Select(c => c["name"].AsString);
            collectionNames.Should().NotContain("fs.files");
            collectionNames.Should().NotContain("fs.chunks");
        }
 protected Task <ObjectId> InvokeMethodAsync(GridFSBucket bucket)
 {
     return(bucket.UploadFromBytesAsync(_filename, _source, _options));
 }
예제 #30
0
파일: FilesRepo.cs 프로젝트: cz303/Pingeo
 public Task Save(string fileId, byte[] file)
 {
     return(_gridFs.UploadFromBytesAsync(fileId, file));
 }
예제 #31
0
        public static async Task <ObjectId> UploadImage(string title, Byte[] bytes)
        {
            var imageId = await _imageBucket.UploadFromBytesAsync(title, bytes);

            return(imageId);
        }
 protected Task<ObjectId> InvokeMethodAsync(GridFSBucket bucket)
 {
     return bucket.UploadFromBytesAsync(_filename, _source, _options);
 }