Ejemplo n.º 1
0
        public byte[] DownloadFile(MongoDB.Bson.ObjectId id)
        {
            var bucket = new GridFSBucket(getDatabase());
            var file   = bucket.DownloadAsBytes(id);

            return(file);
        }
Ejemplo n.º 2
0
        public FuncionarioView GetFuncionario(string CPF)
        {
            try
            {
                // Recupera funcionário pelo CPF informado
                Funcionario funcionario = _context.Funcionarios.Find(x => x.CPF == CPF).FirstOrDefault();

                // Cria novo objeto FuncionarioView e inicializa com valores recuperados do banco
                FuncionarioView data = new FuncionarioView()
                {
                    CPF      = funcionario.CPF,
                    Email    = funcionario.Email,
                    Endereco = funcionario.Endereco,
                    Nome     = funcionario.Nome,
                    Tel      = funcionario.Tel,
                };

                // Recupera imagem do funcionário caso exista
                if (funcionario.Photo != null)
                {
                    byte[] photo        = _gridFS.DownloadAsBytes(funcionario.Photo);
                    string base64string = Convert.ToBase64String(photo, 0, photo.Length);
                    data.FileUrl = "data:image/png;base64," + base64string;
                }

                return(data);
            }
            catch (Exception ex)
            {
                throw new Exception("Não foi possível recuperar funcionário", ex);
            }
        }
Ejemplo n.º 3
0
        public FileData Download(string fileId)
        {
            FileData file = null;

            try
            {
                GridFSBucket   gridFS     = new GridFSBucket(this.GetDB());
                GridFSFileInfo gridFSFile = gridFS.Find(Builders <GridFSFileInfo> .Filter.Eq("_id", new ObjectId(fileId))).FirstOrDefault();
                if (gridFSFile != null)
                {
                    file = new FileData
                    {
                        Id             = fileId,
                        Name           = gridFSFile.Filename,
                        Type           = gridFSFile.Filename.Substring(gridFSFile.Filename.IndexOf('.') + 1),
                        Bytes          = gridFS.DownloadAsBytes(new ObjectId(fileId)),
                        UploadDateTime = gridFSFile.UploadDateTime.ToUniversalTime()
                    };
                }
                else
                {
                    throw new Exception($"cannot find {fileId} file.");
                }
            }
            catch { throw; }
            return(file);
        }
Ejemplo n.º 4
0
        private static string PrepareEnv(Message message)
        {
            lock (GlobalLock)
            {
                if (!Directory.Exists("work"))
                {
                    Directory.CreateDirectory("work");
                }

                //todo: wrap in lock
                var workPath = Path.Combine("work", message.ZipMongoBlobId);
                if (!Directory.Exists(workPath))
                {
                    Directory.CreateDirectory(workPath);


                    var client = new MongoClient(Jobs.MongoConnectionString);
                    var db     = client.GetDatabase(Jobs.MongoBlobsDbName);
                    var bucket = new GridFSBucket(db);

                    if (!ObjectId.TryParse(message.ZipMongoBlobId, out var blobId))
                    {
                        throw new InvalidOperationException($"Can't parse `{message.ZipMongoBlobId}` as ObjectId");
                    }

                    var bytes       = bucket.DownloadAsBytes(blobId);
                    var zipFileName = $"{message.ZipMongoBlobId}.zip";
                    File.WriteAllBytes(zipFileName, bytes);
                    ZipFile.ExtractToDirectory(zipFileName, workPath);
                }

                return(workPath);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// GridFS文件操作——下载
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public byte[] DownLoad(ObjectId fileId)
        {
            var gridfs = new GridFSBucket(database);

            byte[] fileData = gridfs.DownloadAsBytes(fileId);
            return(fileData);
        }
Ejemplo n.º 6
0
        public void DownloadBlob()
        {
            var bucket = new GridFSBucket(db);

            ObjectId.TryParse("5b550d43ad3ef0083c6e3ca7", out var id);
            var data = bucket.DownloadAsBytes(id);
        }
Ejemplo n.º 7
0
        public byte[] ReadImage(string cardNumber)
        {
            MongoClient client = connection();
            var         db     = client.GetDatabase("CreditCardIMG");
            var         bucket = new GridFSBucket(db);
            var         filter = Builders <GridFSFileInfo> .Filter.And(
                Builders <GridFSFileInfo> .Filter.Eq(x => x.Filename, cardNumber));

            var options = new GridFSFindOptions
            {
                Limit = 1
            };

            using (var cursor = bucket.Find(filter, options))
            {
                var fileInfo = cursor.ToList().FirstOrDefault();
                if (fileInfo == null)
                {
                    return(ReadImage("000000001111")); //Image Not Available.
                }
                else
                {
                    var imageToReturn = bucket.DownloadAsBytes(fileInfo.Id);
                    return(imageToReturn);
                }
            }
        }
        public byte[] DownloadGridFsFile(string fileId)
        {
            var bucket = new GridFSBucket(mongoDatabase);
            var id     = new ObjectId(fileId);
            var file   = bucket.DownloadAsBytes(id);

            return(file);
        }
Ejemplo n.º 9
0
        public byte[] DownloadAsBytes(ObjectId id, GridFSDownloadOptions options = null)
        {
            MongoClient client = GetClient(m_connectionStr);
            var         db     = client.GetDatabase(DatabaseName);
            var         bucket = new GridFSBucket(db, BucksOptions);

            return(bucket.DownloadAsBytes(id, options));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获得文件字节数组
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public static Byte[] GetFileBytes(string bucketName, string fileId)
        {
            GridFSBucketOptions options = new GridFSBucketOptions();

            options.BucketName = bucketName;
            var bucket = new GridFSBucket(mongoContext, options);

            return(bucket.DownloadAsBytes(new ObjectId(fileId)));
        }
Ejemplo n.º 11
0
        public IActionResult download(string id)
        {
            var aa = new ObjectId(id);

            var gfs = new GridFSBucket(_db.Registros.Database);

            var k = gfs.DownloadAsBytes(aa);

            return(File(k, "APPLICATION/octet-stream", "aaaaa"));
        }
Ejemplo n.º 12
0
        public byte[] GetImage(string idstring)
        {
            var bucket = new GridFSBucket(db, new GridFSBucketOptions
            {
                BucketName = "UniversityImages",
            });
            ObjectId id = new ObjectId(idstring);

            byte[] bytes = bucket.DownloadAsBytes(id);
            return(bytes);
        }
    private static void RetrieveFromGridFS()
    {
        var bucket = new GridFSBucket(mongoDb, new GridFSBucketOptions {
            BucketName = "pictures"
        });
        var filesIds = mongoDb.GetCollection <BsonDocument>("pictures.files").Find(new BsonDocument()).ToEnumerable().Select(doc => doc.GetElement("_id").Value);

        foreach (var id in filesIds)
        {
            var fileBytes = bucket.DownloadAsBytes(id);
            fileBytes = null;
        }
    }
Ejemplo n.º 14
0
        //public DataTable GetDocmentListByPolicyHolder(string phid)
        //{
        //    PierceMainTableAdapters.MongoDocumentLinkTableAdapter da = new PierceMainTableAdapters.MongoDocumentLinkTableAdapter();
        //    PierceMain.MongoDocumentLinkDataTable dt = new PierceMain.MongoDocumentLinkDataTable();
        //    try
        //    {
        //        da.FillBy(dt, phid);
        //    }
        //    catch (Exception ex)
        //    {
        //        ErrorMessage = ex.Message.ToString();
        //    }

        //    return dt;
        //}

        public string GetOneBucketDocumentById(string fileid)
        {
            SetupMongoDb();
            string newid = string.Empty;

            try
            {
                ObjectId obj = new ObjectId(fileid);
                //var ObjectId = new database.ob('59c2b7df8dff1e3488c16c97');
                var query = Query.EQ("_id", obj);
                //var query = Query.EQ("_id",);
                // db.document.findOne(query);
                //var dbCollection = db.database.GetCollection("pdfs.files");
                //var entity = dbCollection.Find(query);
                ////var intcount = entity.Count();
                //if (entity !=null)
                //{
                //    Debug.WriteLine(entity.ToString());

                //}

                //var fileids = db.database.GetCollection("pdfs.files").Find(query);


                var bucket = new GridFSBucket(mongoDb, new GridFSBucketOptions {
                    BucketName = "pdfs"
                });

                var fileBytes = bucket.DownloadAsBytes(obj);
                var ctr       = fileBytes.Count();
                // Debug.WriteLine(fileBytes);
                string splitstring = fileBytes.ToString();

                Array arrSplit = splitstring.Split(',');
                ctr = arrSplit.Length;
                //string unformatted = arrSplit.GetValue(0).ToString();
                //Array arrsplit2 = unformatted.Split(':');
                //string unformatted2 = arrsplit2.GetValue(1).ToString();
                //int len = unformatted2.Length;
                //int stoplen = len - 13;
                //newid = unformatted2.Substring(11, stoplen);
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message.ToString();
            }



            return(newid);
        }
Ejemplo n.º 15
0
        public IActionResult Get(string id, string name)
        {
            name = HttpUtility.UrlEncode(name);
            bool         checkId  = ObjectId.TryParse(id, out ObjectId objectId);
            var          database = _client.GetDatabase("UploadDB");
            GridFSBucket g        = new GridFSBucket(database);
            var          obj      = checkId ? g.DownloadAsBytes(objectId) : g.DownloadAsBytesByName(name);

            if (obj != null)
            {
                return(File(obj, "application/octet-stream", name));
            }
            return(BadRequest("Not Find!"));
        }
Ejemplo n.º 16
0
        public void PutTest(MongoDatabaseFactory factory, byte[] data)
        {
            var sut = new MongoGridFSDataBus(factory);

            var input = new MemoryStream(data);
            var key   = sut.Put(input, TimeSpan.FromDays(1)).Result;

            var gridFsBucket = new GridFSBucket(factory.GetDatabase());

            var result = gridFsBucket.DownloadAsBytes(ObjectId.Parse(key));

            result.Length.Should().Be(data.Length);
            result.Should().BeEquivalentTo(data);
        }
Ejemplo n.º 17
0
        public ActionResult GetImage(string id)
        {
            var gridFs = new GridFSBucket(Context.MongoDatabase);
            //var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "please-keep-your-voice-down.png");
            var filter = Builders <GridFSFileInfo> .Filter.Eq(x => x.Metadata["Id"], new ObjectId(id));

            var imageFileInfo = gridFs.Find(filter).FirstOrDefault();

            var imageBytes = gridFs.DownloadAsBytes(imageFileInfo.Id);

            if (imageBytes == null)
            {
                return(HttpNotFound());
            }
            return(File(imageBytes, imageFileInfo.Metadata["ContentType"].ToString()));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 从FileBucket下载文件
        /// </summary>
        public byte[] DownloadFile(string filename)
        {
            // 从FileInfo查找文件信息
            var collection = fileInfoDB.GetCollection <BucketFileInfo>(fileInfoDbName);
            var results    = collection.Find(fileInfo => fileInfo.FileName.Equals(filename));

            if (results.Any())
            {
                var id = results.FirstOrDefault().Id;
                return(fsBucket.DownloadAsBytes(id));
            }
            else
            {
                return(new byte[0]);
            }
        }
Ejemplo n.º 19
0
        public FileInfo Get(string id)
        {
            var fileInfo = _fileStore.Get(id);

            if (fileInfo == null)
            {
                throw new ArgumentNullException("未找到此文件");
            }
            var mongdbFileInfo = _gridFSBucket.Find(Builders <GridFSFileInfo <ObjectId> > .Filter.Eq(f => f.Metadata["fileInfoId"], id))
                                 .FirstOrDefault();

            if (mongdbFileInfo != null)
            {
                fileInfo.FileData = _gridFSBucket.DownloadAsBytes(mongdbFileInfo.Id);
            }
            return(fileInfo);
        }
Ejemplo n.º 20
0
        public ActionResult GetImage(string id)
        {
            try
            {
                IGridFSBucket bucket = new GridFSBucket(context.Database);
                // Stream destination= new FileStream(@"C:\image.png",FileMode.OpenOrCreate);



                var bytes = bucket.DownloadAsBytes(new ObjectId(id));
                //var filter = Builders<Rental>.Filter.Where(f => f.ImageId == new ObjectId(id).ToString());
                var aRental = context.Rentals.Find(f => f.ImageId == id).FirstOrDefault();

                return(File(bytes, aRental != null && !String.IsNullOrEmpty(aRental.ImageType) ? aRental.ImageType:"png"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Used to download image from Alerts collection
        /// </summary>
        /// <param name="alert">Single alert field</param>
        /// <param name="imgId">Id of downloading image</param>
        /// <param name="number">ordinal number, must be unique</param>
        /// <returns></returns>
        public string DownloadImage(Alerts alert, ObjectId imgId, int number)
        {
            var bucket = new GridFSBucket(db);
            var bytes  = bucket.DownloadAsBytes(imgId);
            var image  = BytesToImage(bytes);

            string path = alert.StudentFirstAndLastName + "\\" + alert.AlertName;

            //If Directory does not exists then...
            if (!(Directory.Exists(path)))
            {
                Directory.CreateDirectory(path);
            }
            string cleanString = Regex.Replace(alert.AddDate, @"[^0-9]", "_");
            string fileName    = cleanString + "_" + number + ".jpg";

            path = Path.Combine(path, fileName);
            Bitmap b = new Bitmap(image);

            b.Save(path);
            return(path);
        }
Ejemplo n.º 22
0
        public bool DownLoadFiles(String id, string url)
        {
            try
            {
                var option = new GridFSUploadOptions
                {
                };
                var fs         = new GridFSBucket(mongoDB.database);
                var collection = mongoDB.database.GetCollection <Models.File>("fs.files");
                var filter     = Builders <Models.File> .Filter.Eq("_id", ObjectId.Parse(id));

                var result   = collection.Find(filter).ToList();
                var fileDate = result[0];
                var f        = fs.DownloadAsBytes(ObjectId.Parse(id));
                var path     = Path.Combine(url, fileDate.filename);
                System.IO.File.WriteAllBytes(@path, f);
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 23
0
 // protected methods
 protected byte[] InvokeMethod(GridFSBucket bucket)
 {
     return(bucket.DownloadAsBytes(_id, _options));
 }
Ejemplo n.º 24
0
 /// <summary>
 /// 下载成byte数组
 /// </summary>
 /// <param name="id">mongodb主键</param>
 /// <returns></returns>
 public Byte[] DownloadAsByteArray(ObjectId id)
 {
     Byte[] bytes = bucket.DownloadAsBytes(id);
     return(bytes);
 }
Ejemplo n.º 25
0
 public byte[] GetGridFilesById(ObjectId objId)
 {
     return(mGridFSBucket.DownloadAsBytes(objId));
 }
Ejemplo n.º 26
0
 public byte[] DownloadFile(string id)
 {
     return(bucket.DownloadAsBytes(new ObjectId(id)));
 }
        protected override void CallMethod(CancellationToken cancellationToken)
        {
            var bucket = new GridFSBucket(_database, _bucketOptions);

            bucket.DownloadAsBytes(_id, _downloadOptions, cancellationToken);
        }
Ejemplo n.º 28
0
 // protected methods
 protected byte[] InvokeMethod(GridFSBucket bucket)
 {
     return bucket.DownloadAsBytes(_id, _options);
 }
Ejemplo n.º 29
0
        public byte[] Get(string fileReference)
        {
            var fs = new GridFSBucket(_context.Database);

            return(fs.DownloadAsBytes(new ObjectId(fileReference)));
        }