示例#1
0
        public async Task <byte[]> DownLoadFileAsync(string fileName)
        {
            //var id = await GetFileId(fileName);
            var options = new GridFSDownloadOptions
            {
            };
            var bytes = await bucket.DownloadAsBytesAsync(fileName);

            return(bytes);
        }
        public async Task <byte[]> GetChallengeImage(string challengeId)
        {
            var challenge = await GetChallengeAsync(challengeId);

            if (challenge == null)
            {
                return(null);
            }

            return(await _gridFS.DownloadAsBytesAsync(new ObjectId(challenge.ImageId)));
        }
示例#3
0
        public async Task <Tuple <string, byte[]> > GetFile(string guid)
        {
            var id    = ObjectId.Parse(guid);
            var query = await gridFs.FindAsync(Builders <GridFSFileInfo> .Filter.Eq("_id", id));

            var file = await query.SingleOrDefaultAsync();

            if (file == null)
            {
                throw new Exception(string.Format("File not found (id: {0})", guid));
            }
            var array = await gridFs.DownloadAsBytesAsync(id);

            return(Tuple.Create(file.Filename, array));
        }
示例#4
0
        public async Task <Picture?> Get(ObjectId pictureId)
        {
            var pictures = await _pictures.FindAsync(p => p.Id == pictureId);

            var pictureEntities = pictures.Current.ToList();

            if (!pictureEntities.Any())
            {
                return(null);
            }
            _logger.LogDebug($"Got pictures from mongo: {string.Concat(pictureEntities.Select(e => e.ToString()))}");
            var picture = pictures.First();
            var filter  = Builders <GridFSFileInfo> .Filter.Eq("_id", picture.GridFsIds.Last());

            var fileInfos = await _gridFs.FindAsync(filter);

            var fileInfo = fileInfos.FirstOrDefault();

            if (fileInfo == null)
            {
                return(null);
            }
            var pic = await _gridFs.DownloadAsBytesAsync(picture.Id);

            _logger.LogInformation($"Got picture data for {pictureId} with length {pic.Length}");

            return(new Picture(pic, picture.Filename, picture.Id, picture.Width, picture.Height));
        }
        public async Task <IFileResponse> GetPostFileAsync(string fileId)
        {
            try
            {
                var bucket = new GridFSBucket(_mongoDbContext.Database);
                var file   = new FileView();
                using (var stream = await bucket.OpenDownloadStreamAsync(new ObjectId(fileId)))
                {
                    if (stream == null)
                    {
                        return(new FileResponse(ClientMessageConstant.FileNotFound, HttpStatusCode.NotFound));
                    }
                    file.FileBytes = await bucket.DownloadAsBytesAsync(new ObjectId(fileId));

                    file.Name     = stream.FileInfo.Filename;
                    file.MimeType = stream.FileInfo.ContentType;
                }

                return(new FileResponse(file));
            }
            catch (Exception e)
            {
                return(new FileResponse(e));
            }
        }
示例#6
0
        public async Task <byte[]> GetDataAsync(string id)
        {
            var coll = GetCollection <MemoryItemModel>(MemoryVaultCollections.Memories);

            var filter = Builders <MemoryItemModel> .Filter.Eq(p => p.Id, ObjectId.Parse(id));

            var project = Builders <MemoryItemModel> .Projection.Expression(e => e.ItemId);

            var proj = new FindOptions <MemoryItemModel, ObjectId>
            {
                Projection = project
            };

            var found = await coll.FindAsync(filter, proj);

            var fileId = await found.FirstOrDefaultAsync();

            if (fileId != null)
            {
                GridFSBucketOptions opts = new GridFSBucketOptions();
                opts.BucketName = MemoryVaultCollections.MemoryFiles;

                var bucket = new GridFSBucket(GetDatabase(), opts);

                return(await bucket.DownloadAsBytesAsync(fileId));
            }

            return(null);
        }
        public async Task DownloadFileMongo()
        {
            var client = new MongoClient("mongodb://localhost:27017");

            var database = client.GetDatabase("BookstoreDb");

            var gridFsBucketOptions = new GridFSBucketOptions()
            {
                BucketName     = "images",
                ChunkSizeBytes = 1048576, // 1МБ
            };

            var bucket = new GridFSBucket(database, gridFsBucketOptions);

            var filter = Builders <GridFSFileInfo <ObjectId> >

                         .Filter.Eq(x => x.Filename, "123.png");

            var searchResult = await bucket.FindAsync(filter);

            var fileEntry = searchResult.FirstOrDefault();

            byte[] content = await bucket.DownloadAsBytesAsync(fileEntry.Id);

            File.WriteAllBytes("123.png", content);
        }
        /// <summary>
        /// GridFS文件操作——下载
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        async public Task <byte[]> DownLoadAsync(ObjectId fileId)
        {
            var gridfs = new GridFSBucket(database);

            byte[] fileData = await gridfs.DownloadAsBytesAsync(fileId);

            return(fileData);
        }
示例#9
0
 public async Task <byte[]> DownloadFile(ObjectId id, CancellationToken token = default(CancellationToken))
 {
     if (_bucket == null)
     {
         return(null);
     }
     return(await _bucket.DownloadAsBytesAsync(id, cancellationToken : token));
 }
示例#10
0
        public async Task <byte[]> DownloadAsBytesAsync(ObjectId id, GridFSDownloadOptions options = null)
        {
            MongoClient client = GetClient(m_connectionStr);
            var         db     = client.GetDatabase(DatabaseName);
            var         bucket = new GridFSBucket(db, BucksOptions);

            return(await bucket.DownloadAsBytesAsync(id, options));
        }
示例#11
0
        public async Task <FileModel> GetFile(string fileId)
        {
            var filter = Builders <GridFSFileInfo <ObjectId> > .Filter.Eq(x => x.Id, new ObjectId(fileId));

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

            if (currentFile == null)
            {
                return(null);
            }

            byte[] bytes = await _gridFS.DownloadAsBytesAsync(currentFile.Id);

            return(new FileModel()
            {
                Filename = currentFile.Filename,
                Data = bytes
            });
        }
示例#12
0
        /*
         * Profile picture related functions
         */
        public async Task <byte[]> GetTeamImage(string teamId)
        {
            var team = await GetTeamAsync(teamId);

            if (team == null || string.IsNullOrWhiteSpace(team.ImageId))
            {
                return(null);
            }

            return(await _gridFS.DownloadAsBytesAsync(new ObjectId(team.ImageId)));
        }
示例#13
0
        /*
         * Profile picture related functions
         */
        public async Task <byte[]> GetProfilePicture(string userId)
        {
            var user = await GetUserAsync(userId);

            if (user == null || string.IsNullOrWhiteSpace(user.ProfilePictureId))
            {
                return(null);
            }

            return(await _gridFS.DownloadAsBytesAsync(new ObjectId(user.ProfilePictureId)));
        }
示例#14
0
        private void DownloadFile(GridFSBucket fs, ObjectId id)
        {
            var x = fs.DownloadAsBytesAsync(id);

            Task.WaitAll(x);
            var bytes = x.Result;

            var stream = new MemoryStream(bytes);

            pictureBox2.Image = Image.FromStream(stream);
        }
示例#15
0
        public async Task <IActionResult> GetImage(string id)
        {
            var bucket = new GridFSBucket(Context.Database);
            var image  = await bucket.DownloadAsBytesAsync(new ObjectId(id));

            var   base64 = Convert.ToBase64String(image);
            var   imgSrc = String.Format("data:image/jpeg;base64,{0}", base64);
            Image i      = new Image()
            {
                ImageHash = imgSrc
            };

            return(Ok(i));
        }
示例#16
0
        private static void DownloadFile(GridFSBucket fs, ObjectId id)
        {
            //This works
            var t = fs.DownloadAsBytesByNameAsync("test.txt");

            Task.WaitAll(t);
            var bytes = t.Result;


            //This blows chunks (I think it's a driver bug, I'm using 2.1 RC-0)
            var x = fs.DownloadAsBytesAsync(id);

            Task.WaitAll(x);
        }
        public async Task <IFileResponse> GetMessagingImageFileAsync(string roomId)
        {
            try
            {
                var file = new FileView();
                var room = await _mongoDbContext.Rooms.Find(k => k.ID == new ObjectId(roomId)).FirstOrDefaultAsync();

                if (room == null)
                {
                    return(new FileResponse(ClientMessageConstant.PostNotFound, HttpStatusCode.NotFound));
                }

                //if (room.Messages. == (int)PostType.Image)
                //{
                var fileId = room.Messages.FirstOrDefault().ImagesIDs.ToString();

                if (fileId == null)
                {
                    return(new FileResponse(file));
                }

                var bucket = new GridFSBucket(_mongoDbContext.Database);

                using (var stream = await bucket.OpenDownloadStreamAsync(new ObjectId(fileId)))
                {
                    if (stream == null)
                    {
                        return(new FileResponse(ClientMessageConstant.FileNotFound, HttpStatusCode.NotFound));
                    }
                    file.FileBytes = await bucket.DownloadAsBytesAsync(new ObjectId(fileId));

                    file.Name     = stream.FileInfo.Filename;
                    file.MimeType = stream.FileInfo.ContentType;
                }
                //}
                //else
                //{
                //  return new FileResponse(ClientMessageConstant.ImagePostNotExist, HttpStatusCode.NotFound);
                //}


                return(new FileResponse(file));
            }
            catch (Exception e)
            {
                return(new FileResponse(e));
            }
        }
        public async Task <IFileResponse> GetPostImageAsync(string postId)
        {
            try
            {
                var file = new FileView();
                var post = await _mongoDbContext.Posts.Find(k => k.ID == new ObjectId(postId)).FirstOrDefaultAsync();

                if (post == null)
                {
                    return(new FileResponse(ClientMessageConstant.PostNotFound, HttpStatusCode.NotFound));
                }

                if (post.TypeID == (int)PostType.Image)
                {
                    var fileId = post.ImageIDs.FirstOrDefault();

                    if (fileId == null)
                    {
                        return(new FileResponse(file));
                    }

                    var bucket = new GridFSBucket(_mongoDbContext.Database);

                    using (var stream = await bucket.OpenDownloadStreamAsync(new ObjectId(fileId)))
                    {
                        if (stream == null)
                        {
                            return(new FileResponse(ClientMessageConstant.FileNotFound, HttpStatusCode.NotFound));
                        }
                        file.FileBytes = await bucket.DownloadAsBytesAsync(new ObjectId(fileId));

                        file.Name     = stream.FileInfo.Filename;
                        file.MimeType = stream.FileInfo.ContentType;
                    }
                }
                else
                {
                    return(new FileResponse(ClientMessageConstant.ImagePostNotExist, HttpStatusCode.NotFound));
                }
                return(new FileResponse(file));
            }
            catch (Exception e)
            {
                return(new FileResponse(e));
            }
        }
        public async Task <byte[]> LoadPdfAsync(string fileName)
        {
            var gridFsBucket = new GridFSBucket(_database);
            var filter       = Builders <GridFSFileInfo> .Filter.Eq(x => x.Filename, fileName);

            var finData = await gridFsBucket.FindAsync(filter);

            var firstData = finData.FirstAsync().Result;
            var bsonId    = firstData.Id;

            byte[] content = await gridFsBucket.DownloadAsBytesAsync(firstData.Id);

            //  var dataStream = await gridFsBucket.OpenDownloadStreamAsync(bsonId);


            return(content);
        }
        public static async Task DownloadFileAsBytes()
        {
            var database = DatabaseHelper.GetDatabaseReference("localhost", "file_store");

            IGridFSBucket bucket = new GridFSBucket(database);

            var filter = Builders <GridFSFileInfo <ObjectId> > .Filter.Eq(x => x.Filename, "sample2.pdf");

            var searchResult = await bucket.FindAsync(filter);

            var fileEntry = searchResult.FirstOrDefault();

            byte[] content = await bucket.DownloadAsBytesAsync(fileEntry.Id);

            File.WriteAllBytes("C:\\temp\\sample3.pdf", content);

            //System.Diagnostics.Process.Start("C:\\temp\\sample2.pdf");
        }
示例#21
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <MongoDbFileDoc> DownLoadFile(string id)
        {
            var model  = new MongoDbFileDoc();
            var filter = Builders <GridFSFileInfo <ObjectId> > .Filter.Eq(x => x.Id, new ObjectId(id));

            var bucket   = new GridFSBucket(GetMongoDatabase(), new GridFSBucketOptions());
            var fileInfo = await bucket.FindAsync(filter);

            var file = await fileInfo.FirstOrDefaultAsync();

            if (file != null)
            {
                model.FileName  = file.Filename;
                model.FileId    = id;
                model.FileBytes = await bucket.DownloadAsBytesAsync(new ObjectId(id));
            }

            return(model);
        }
        public List <byte[]> DownloadFile(GridFSBucket fs, List <ObjectId> id)
        {
            string        path    = @"G:\Projekty\WebAppParser\Content\images\";
            List <string> files   = Utils.FilesInFolder(path);
            List <byte[]> result  = new List <byte[]>();
            int           counter = 0;

            foreach (string file in files)
            {
                var t = fs.DownloadAsBytesByNameAsync(file);
                Task.WaitAll(t);
                var bytes = t.Result;
                var x     = fs.DownloadAsBytesAsync(id[counter++]);
                Task.WaitAll(x);
                result.Add(x.Result);
            }

            return(result);
        }
示例#23
0
        public EventIn Get(string id)
        {
            Event    events = _event.Find <Event>(tempEvent => tempEvent.Id == id).FirstOrDefault();
            ObjectId temp   = ObjectId.Parse(events.EventFileID);
            var      x      = bucket.DownloadAsBytesAsync(temp);

            Task.WaitAll(x);
            EventIn eventIn = new EventIn()
            {
                Id          = events.Id,
                VideoURL    = events.VideoURL,
                Name        = events.Name,
                Location    = events.Location,
                Date        = events.Date,
                TimeStart   = events.TimeStart,
                TimeEnd     = events.TimeEnd,
                Description = events.Description,
                EventFile   = x.Result
            };

            return(eventIn);
        }
示例#24
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);
        }
示例#25
0
 /// <summary>
 /// 下载文件
 /// </summary>
 public async Task <byte[]> GetFileBytesAsync(string id)
 {
     return(await _bucket.DownloadAsBytesAsync(new ObjectId(id)));
 }
 protected Task<byte[]> InvokeMethodAsync(GridFSBucket bucket)
 {
     return bucket.DownloadAsBytesAsync(_id, _options);
 }
示例#27
0
 public async Task <byte[]> GetImage(string id)
 {
     return(await _gridFS.DownloadAsBytesAsync(new ObjectId(id)));
 }
 protected override async Task CallMethodAsync(CancellationToken cancellationToken)
 {
     var bucket = new GridFSBucket(_database, _bucketOptions);
     await bucket.DownloadAsBytesAsync(_id, _downloadOptions, cancellationToken).ConfigureAwait(false);
 }
示例#29
0
        public async Task <byte[]> GetAsync(string fileReference)
        {
            var fs = new GridFSBucket(_context.Database);

            return(await fs.DownloadAsBytesAsync(new ObjectId(fileReference)));
        }
示例#30
0
 // protected methods
 protected Task <byte[]> InvokeMethodAsync(GridFSBucket bucket)
 {
     return(bucket.DownloadAsBytesAsync(_id, _options));
 }
示例#31
0
        private async Task <File> LoadByteContentForFile(File file)
        {
            file.FileContent = await _bucket.DownloadAsBytesAsync(file.FileId.ToObjectId());

            return(file);
        }