예제 #1
0
        public async Task CopyFileAsync(string srcPath, string dstPath)
        {
            var physicalSrcPath = GetPhysicalPath(srcPath);

            if (await getGridFSFileInfoAsync(physicalSrcPath) == null)
            {
                throw new FileStoreException($"The file '{srcPath}' does not exist.");
            }

            var physicalDstPath = GetPhysicalPath(dstPath);

            if (await getGridFSFileInfoAsync(physicalDstPath) != null)
            {
                throw new FileStoreException($"Cannot copy file because the destination path '{dstPath}' already exists.");
            }


            var stream = await _bucket.OpenDownloadStreamByNameAsync(physicalSrcPath);

            var response = await _bucket.UploadFromStreamAsync(physicalDstPath, stream);

            if (response == null)
            {
                throw new FileStoreException($"Cannot copy file '{srcPath}'.");
            }
        }
예제 #2
0
        private ObjectId UploadFile(GridFSBucket fs, Stream stream)
        {
            var file = File.OpenRead(nfile);
            var t    = Task.Run <ObjectId>(() => fs.UploadFromStreamAsync("test.txt", file));

            return(t.Result);
        }
예제 #3
0
        public async Task <IActionResult> AddImage(string id, IFormFile file)
        {
            if (file == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var rental = await GetRentalById(id);

            using (Stream stream = file.OpenReadStream())
            {
                var bucket = new GridFSBucket(Context.Database);
                GridFSUploadOptions options = new GridFSUploadOptions()
                {
                    ContentType = file.ContentType
                };

                var fileInfo = await bucket.UploadFromStreamAsync(file.FileName, stream, options);

                rental.ImageId = fileInfo.ToString();
            }

            await Context.Rentals.ReplaceOneAsync(new BsonDocument("_id", new ObjectId(id)), rental, new UpdateOptions { IsUpsert = true });

            return(Ok(true));
        }
예제 #4
0
        private async Task <ObjectId> UploadVideo(string title, string link)
        {
            using var downloadClient       = new WebClient();
            await using var downloadStream = await downloadClient.OpenReadTaskAsync(link);

            return(await _videos.UploadFromStreamAsync(title, downloadStream));
        }
        private async Task MigratePortraits(CancellationToken cancellationToken)
        {
            var source = new GridFSBucket(_source, new GridFSBucketOptions
            {
                BucketName = "portraits"
            });

            using (var cursor = await source.FindAsync(Builders <GridFSFileInfo> .Filter.Empty))
            {
                var files = await cursor.ToListAsync();

                var destination = new GridFSBucket(_destination, new GridFSBucketOptions
                {
                    BucketName = "portraits"
                });

                foreach (var file in files)
                {
                    using (var stream = await source.OpenDownloadStreamByNameAsync(file.Filename, null, cancellationToken))
                    {
                        await destination.UploadFromStreamAsync(file.Filename, stream, null, cancellationToken);
                    }
                }
            }
        }
예제 #6
0
        public async Task <ObjectId> UploadMedia(Stream data, string filename, ObjectId owner)
        {
            var id = ObjectId.GenerateNewId();

            if (string.IsNullOrWhiteSpace(filename))
            {
                filename = $"{owner}_{id}";
            }
            var ext = Path.GetExtension(filename);

            if (string.IsNullOrWhiteSpace(ext))
            {
                ext      = data.GetImageExt();
                filename = $"{filename}{ext}";
            }
            var mediaId = await _gridFS.UploadFromStreamAsync(filename, data);

            var media = new Media
            {
                Ext       = ext,
                Filename  = filename,
                Id        = id,
                MediaId   = mediaId,
                MediaType = Media.GetMediaType(filename),
                ViewCount = 0,
                Owner     = owner
            };

            await _media.InsertOneAsync(media);

            return(media.Id);
        }
예제 #7
0
        public async Task SaveFile(int id, string consumer, Stream file)
        {
            var client = GetClient();

            using (var session = await client.StartSessionAsync())
            {
                session.StartTransaction();

                var fileDoc = new FileDocument
                {
                    Id       = id,
                    Consumer = consumer,
                    FileName = $"{id}_{consumer}",
                    State    = FileState.Uploaded
                };

                var bucket = new GridFSBucket(client.GetDatabase(_url.DatabaseName), new GridFSBucketOptions {
                    BucketName = "Uploads"
                });
                await bucket.UploadFromStreamAsync(fileDoc.FileName, file);

                var collection = client.GetDatabase(_url.DatabaseName).GetCollection <FileDocument>(CollectionName);
                await collection.InsertOneAsync(fileDoc);

                await session.CommitTransactionAsync();
            }
        }
예제 #8
0
        public async Task <ObjectId> UploadFromStreamAsync(Stream 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.UploadFromStreamAsync(fileName, source, options));
        }
예제 #9
0
        protected override async Task Handle(RegisterPortraitCommand command, CancellationToken cancellationToken)
        {
            var bucket = new GridFSBucket(_database, new GridFSBucketOptions
            {
                BucketName = "portraits"
            });

            await bucket.UploadFromStreamAsync(command.Name, command.Image, null, cancellationToken);
        }
예제 #10
0
        /// <summary>
        /// GridFS文件操作——上传 异步
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileStream"></param>
        /// <returns></returns>
        async public Task <ObjectId> UpLoadAsync(string fileName, Stream fileStream)
        {
            var gridfs = new GridFSBucket(database, new GridFSBucketOptions
            {
            });
            ObjectId oId = await gridfs.UploadFromStreamAsync(fileName, fileStream);

            return(oId);
        }
예제 #11
0
        private static ObjectId UploadFile(GridFSBucket fs)
        {
            using (var s = File.OpenRead(@"c:\temp\test.txt"))
            {
                var t = Task.Run <ObjectId>(() => { return
                                                    (fs.UploadFromStreamAsync("test.txt", s)); });

                return(t.Result);
            }
        }
예제 #12
0
        public static async Task UploadPhoto(this ControllerBase controller, string foto, GridFSBucket <ObjectId> gridFsBucket, User user, DateTime creationDate)
        {
            if (string.IsNullOrWhiteSpace(foto))
            {
                user.Avatar = null;
                return;
            }
            var photo = ImageUtils.FromBytes(Convert.FromBase64String(foto));

            if (photo == null)
            {
                controller.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                throw new ResultException
                      (
                          new ObjectResult
                          (
                              new ResponseBody()
                {
                    Code    = ResponseCode.InvalidImage,
                    Success = false,
                    Message = "A imagem enviada é inválida!",
                }
                          )
                      );
            }
            photo = ImageUtils.GuaranteeMaxSize(photo, 1000);
            var photoStream = ImageUtils.ToStream(photo);
            var fileId      = ObjectId.GenerateNewId(creationDate);
            var fileInfo    = new FileInfo
            {
                FileMetadata = new FileMetadata
                {
                    ContentType = "image/jpeg",
                    FileType    = FileType.Image
                },
                Size = photoStream.Length,
            };

            user.Avatar = new FileReference
            {
                _id      = fileId,
                FileInfo = fileInfo
            };
            Task photoTask = gridFsBucket.UploadFromStreamAsync(
                fileId,
                fileId.ToString(),
                photoStream,
                new GridFSUploadOptions()
            {
                Metadata = fileInfo.FileMetadata.ToBsonDocument()
            }
                );
            var   streamCloseTask = photoTask.ContinueWith(tsk => photoStream.Close(), TaskContinuationOptions.ExecuteSynchronously);
            await photoTask;
        }
예제 #13
0
        /// <inheritdoc />
        public async Task Save(string id, Stream source, Dictionary <string, string> metadata = null)
        {
            var metadataDocument = metadata?.ToBsonDocument() ?? new BsonDocument();

            metadataDocument[MetadataKeys.SaveTime] = _rebusTime.Now.ToString("o");

            await _bucket.UploadFromStreamAsync(id, source, new GridFSUploadOptions
            {
                Metadata = metadataDocument
            });
        }
예제 #14
0
        public static void UploadTests()
        {
            var elkUrl     = new Uri("http://*****:*****@"D:\files\testdoc0.docx"))
            {
                bucket.UploadFromStreamAsync(Guid.NewGuid(), "testdoc0.docx", fileStream).Wait();
            }
        }
예제 #15
0
        public async Task <FileDetails> UploadFileAsync(Stream inputStream, FileDetails fileDetails)
        {
            var id = await fsBucket.UploadFromStreamAsync(fileDetails.Name, inputStream);

            fileDetails.Id = id.ToString();

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

            return(fileDetails);
        }
        private async Task StoreImageAsync(HttpPostedFileBase file, string rentalId)
        {
            var bucket  = new GridFSBucket(Context.Database);
            var options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument("contentType", file.ContentType)
            };
            var imageId = await bucket.UploadFromStreamAsync(file.FileName, file.InputStream, options);

            SetRentalImageId(rentalId, imageId.ToString());
        }
예제 #17
0
        private static ObjectId UploadFile(GridFSBucket fs)
        {
            using (var s = File.OpenRead(@"C:\Users\38160\Desktop\Na Drini cuprija.pdf"))
            {
                var t = Task.Run <ObjectId>(() => {
                    return
                    (fs.UploadFromStreamAsync("Na Drini cuprija.pdf", s));
                });

                return(t.Result);
            }
        }
예제 #18
0
        public async Task GridFS(string filePath)
        {
            var fileName = Path.GetFileName(filePath);
            var db       = GetDB();

            IGridFSBucket gridFS = new GridFSBucket(db);

            using (Stream fs = new FileStream(filePath, FileMode.Open))
            {
                ObjectId id = await gridFS.UploadFromStreamAsync(fileName, fs);
            }
        }
예제 #19
0
        public async Task <ObjectId> UploadFileAsync(string path, string bucketname, int chuncksSize = 64512)
        {
            var bucket = new GridFSBucket(database, new GridFSBucketOptions
            {
                ChunkSizeBytes = chuncksSize,
                BucketName     = bucketname
            });

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                return(await bucket.UploadFromStreamAsync(path, stream));
            }
        }
예제 #20
0
        public async Task <String> SaveImage(String image)
        {
            image = image.Replace("data:image/jpeg;base64,", String.Empty)
                    .Replace("data:image/png;base64,", String.Empty)
                    .Replace("data:image/gif;base64,", String.Empty)
                    .Replace("data:image/bmp;base64,", String.Empty);
            byte[] toBytes = Convert.FromBase64String(image);

            using (Stream mystream = new MemoryStream(toBytes)) {
                var myId = await _imagesBucket.UploadFromStreamAsync(String.Empty, mystream);

                return(myId.ToString());
            }
        }
예제 #21
0
        public async Task <ObjectId> StoreImageAsync(string filename)
        {
            var options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument("contentType", "image/jpeg")
            };

            using (var fs = new FileStream(filename, FileMode.Open))
            {
                var imageId = await ImagesBucket
                              .UploadFromStreamAsync(filename, fs, options);

                return(imageId);
            }
        }
예제 #22
0
        public override async Task <string> SaveAsync(Stream stream, string fileName, string contentType)
        {
            var uploadOptions = new GridFSUploadOptions()
            {
                Metadata = new BsonDocument
                {
                    { ContentType, contentType },
                }
            };

            var newId = ObjectId.GenerateNewId();
            await _bucket.UploadFromStreamAsync(newId, fileName, stream, uploadOptions);

            return(newId.ToString());
        }
예제 #23
0
        public async Task <ObjectResult> UploadImageAsync(IFormFile formFile)
        {
            var imageId = ObjectId.GenerateNewId();

            var bucket = new GridFSBucket(context.Database);
            GridFSUploadOptions options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument("contentType", formFile.ContentType)
            };

            var imgId = await bucket.UploadFromStreamAsync(formFile.FileName,
                                                           formFile.OpenReadStream(), options);

            return(new ObjectResult(imgId));
        }
예제 #24
0
        protected void up_Click(object sender, EventArgs e)
        {
            MongoClient client      = new MongoClient(ConfigurationManager.AppSettings["connectionString"]);
            MongoClient mongo       = new MongoClient();
            var         settings    = new MongoClientSettings {
            };
            var    db               = client.GetDatabase("MCS");
            string destination_name = token_no.ToString() + "_" + fact_name.ToString() + ".pdf";

            var options = new GridFSUploadOptions
            {
                // ChunkSizeBytes = 64512 , // 63KB
                Metadata = new BsonDocument
                {
                    { "session_code", Label5.Text.ToString() },
                    { "token_no", token_no.Text.ToString() },
                    { "status", pft_status.SelectedValue },
                    { "advice", advice.Text },
                    { "test", "xray" }
                }
            };

            GridFSBucket bucket = new GridFSBucket(db);

            using (var s = File.OpenRead(path.Text.ToString()))
            {
                var t = Task.Run(() =>
                {
                    return(bucket.UploadFromStreamAsync(destination_name.ToString(), s, options));
                });

                Label8.Text = t.Result.ToString();
            }

            prompt.form_status("Entry saved successfully.");
            path.Visible             = false;
            up.Visible               = false;
            attach.Visible           = false;
            browser.Visible          = false;
            path.Text                = "";
            pft_status.SelectedValue = "Normal";
            advice.Text              = "";
            w_age.Text               = "";
            w_name.Text              = "";
            w_sex.Text               = "";
            token_no.Text            = "";
        }
예제 #25
0
        public async Task <ObjectId> UploadFromStreamAsync(IFormFile file, MediaTypeEnum bucketName)
        {
            var bucket = new GridFSBucket(_mongoDatabase, new GridFSBucketOptions
            {
                BucketName = bucketName.ToString()
            });

            var options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument {
                    { "filename", file.FileName },
                    { "contentType", file.ContentType }
                }
            };

            return(await bucket.UploadFromStreamAsync(file.FileName, file.OpenReadStream(), options));
        }
예제 #26
0
        public async Task UploadAsync(FileDataModel fileDataModel, bool isUpoadOnly = false)
        {
            var document = new BsonDocument();

            InitFileDocument(document, fileDataModel);

            var gridFs     = new GridFSBucket(_database);
            var gridFsInfo = await gridFs.UploadFromStreamAsync(fileDataModel.FileData.FileName, fileDataModel.FileData.Stream,
                                                                new GridFSUploadOptions
            {
                Metadata    = document,
                ContentType = fileDataModel.FileData.ContentType,
            });

            var fileId = gridFsInfo.ToString();

            fileDataModel.Id = fileId;
        }
예제 #27
0
        private static ObjectId UploadFile(GridFSBucket fs, HttpPostedFileBase imageFile)
        {
            try
            {
                var t = Task.Run <ObjectId>(() =>
                {
                    return
                    (fs.UploadFromStreamAsync(imageFile.FileName, imageFile.InputStream));
                });

                return(t.Result);
            }

            catch (Exception ex)
            {
                throw;
            }
        }
        public static async Task <BsonObjectId> ImageUploadAsync(string photo, string name)
        {
            BsonObjectId id = null;

            try
            {
                using (var fs = new FileStream(photo, FileMode.Open))
                {
                    id = await gridFS.UploadFromStreamAsync(name, fs);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in MongoDBTransanctions.ImageUploadAsync() method :: "
                                  + e.Message);
            }

            return(id);
        }
예제 #29
0
파일: Blob.cs 프로젝트: hMatoba/Sokyu
        public static async Task PutAsync(string filename, Stream stream)
        {
            var db         = DbConnection.db;
            var collection = db.GetCollection <GridFSFileInfo>("fs.files");
            var bucket     = new GridFSBucket(db);

            var builder = Builders <GridFSFileInfo> .Filter;
            var filter  = builder.Eq(i => i.Filename, filename);
            var foo     = await collection.FindAsync <GridFSFileInfo>(filter);

            var foooo = foo.ToList();

            foreach (var el in foooo)
            {
                await bucket.DeleteAsync(el.Id);
            }

            var id = await bucket.UploadFromStreamAsync(filename, stream);
        }
예제 #30
0
        private async Task Process(FileStoreMessage message)
        {
            var elkUrl     = new Uri("http://localhost:9200/");
            var connection = new ConnectionSettings(elkUrl);
            var bucket     = new GridFSBucket(connection);

            var fileName = message.Filepath.Split('\\').Last();

            Console.WriteLine($"Uploading the file {fileName}.");
            var timer = new Stopwatch();

            timer.Start();

            using (var fileStream = File.OpenRead(message.Filepath))
            {
                await bucket.UploadFromStreamAsync(Guid.NewGuid(), fileName, fileStream);
            }
            timer.Stop();
            Console.WriteLine($"Upload of file {fileName} has finished. Elaspsed time: {timer.ElapsedMilliseconds} ms.");
        }