コード例 #1
0
        public async Task <string> UploadFile(string filePath)
        {
            await using (var fs = new FileStream(filePath, FileMode.Open))
            {
                var id = await _gridfs.UploadFromStreamAsync(Path.GetFileName(filePath), fs);

                return(id.ToString());
            }
        }
コード例 #2
0
        public async Task UploadAsync(string fileName, Stream stream, bool overwrite = false,
                                      CancellationToken ct = default)
        {
            Guard.NotNull(stream, nameof(stream));

            var name = GetFileName(fileName, nameof(fileName));

            try
            {
                if (overwrite)
                {
                    await DeleteAsync(fileName, ct);
                }

                await bucket.UploadFromStreamAsync(name, name, stream, cancellationToken : ct);
            }
            catch (MongoWriteException ex) when(ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
            {
                throw new AssetAlreadyExistsException(fileName);
            }
            catch (MongoBulkWriteException <BsonDocument> ex) when(ex.WriteErrors.Any(x => x.Category == ServerErrorCategory.DuplicateKey))
            {
                throw new AssetAlreadyExistsException(fileName);
            }
        }
コード例 #3
0
        private async Task UploadFileCoreAsync(FileInfo file, Stream stream,
                                               CancellationToken ct = default(CancellationToken))
        {
            try
            {
                // upload file to GridFS first
                await bucket.UploadFromStreamAsync(file.Name, file.Name, stream, cancellationToken : ct);

                // reset stream position
                stream.Position = 0;

                // create file locally
                // even if this stage will fail, file will be recreated on the next Download call
                using (var fileStream = file.OpenWrite())
                {
                    await stream.CopyToAsync(fileStream, BufferSize, ct);
                }
            }
            catch (IOException ex)
            {
                throw new IOException($"Cannot write file '{file.Name}' into directory '{directory.FullName}'.", ex);
            }
            catch (GridFSException ex)
            {
                throw new GridFSException(
                          $"Cannot upload file {file.Name} into Mongo GridFS bucket '{bucket.Options.BucketName}'.",
                          ex);
            }
        }
コード例 #4
0
        /// <summary>
        /// Сохранить файл в стор
        /// </summary>
        /// <param name="file">файл</param>
        /// <param name="cancellationToken">токен признака отмены</param>
        /// <returns>Идентификатор сохранённого файла</returns>
        public async Task <String> SaveFileAsync(IFormFile file, CancellationToken cancellationToken)
        {
            var hash = await GetHash(file, cancellationToken);

            var filter = Builders <GridFSFileInfo> .Filter.Eq(info => info.Metadata["hash"], hash);

            var existsFiles = await _gridFs.FindAsync(filter, cancellationToken : cancellationToken);

            var existsFile = await existsFiles.FirstOrDefaultAsync(cancellationToken);

            if (existsFile != null)
            {
                return(existsFile.Metadata["FileName"].AsString);
            }

            var fileName = Guid.NewGuid().ToString();
            var metaData = new Dictionary <String, Object>
            {
                ["ContentType"]    = file.ContentType,
                ["length"]         = file.Length,
                ["NonUniqueExtId"] = file.FileName,
                ["FileName"]       = fileName,
                ["hash"]           = hash,
            };
            await _gridFs.UploadFromStreamAsync(
                fileName,
                file.OpenReadStream(),
                new GridFSUploadOptions
            {
                Metadata = new BsonDocument(metaData)
            }, cancellationToken);

            return(fileName);
        }
コード例 #5
0
        public async Task CopyAsync(string name, string id, long version, string suffix, CancellationToken ct = default(CancellationToken))
        {
            try
            {
                var target = GetFileName(id, version, suffix);

                using (var readStream = await bucket.OpenDownloadStreamAsync(name, cancellationToken: ct))
                {
                    await bucket.UploadFromStreamAsync(target, target, readStream, cancellationToken : ct);
                }
            }
            catch (GridFSFileNotFoundException ex)
            {
                throw new AssetNotFoundException($"Asset {name} not found.", ex);
            }
        }
コード例 #6
0
        /// <inheritdoc />
        public async Task <string> StoreFile(string fileName, Stream fileStream)
        {
            var objectId = await _bucket.UploadFromStreamAsync(
                fileName, fileStream);

            return(objectId.ToString());
        }
コード例 #7
0
        // сохранение изображения
        public async Task StoreImage(string id, Stream imageStream, string imageName)
        {
            // если ранее уже была прикреплена картинка, удаляем ее
            await _gridFS.DeleteAsync(new ObjectId(id));

            // сохраняем изображение
            ObjectId imageId = await _gridFS.UploadFromStreamAsync(imageName, imageStream);
        }
        public async Task <Uri> Put(Stream stream, TimeSpan?timeToLive = null, CancellationToken cancellationToken = new CancellationToken())
        {
            var options = BuildGridFSUploadOptions(timeToLive);

            var id = await _gridFsBucket.UploadFromStreamAsync(_randomFileNameCreator.CreateFileName(), stream, options, cancellationToken)
                     .ConfigureAwait(false);

            return(_mongoMessageUriResolver.Resolve(id));
        }
コード例 #9
0
        public async Task <string> SaveFile(MemoryStream ms, string fileName, FileTypeEnum fileType)
        {
            GridFSUploadOptions options = new GridFSUploadOptions
            {
                Metadata = new BsonDocument()
                {
                    { "type", fileType }
                }
            };
            ObjectId imageId = await _gridFS.UploadFromStreamAsync(fileName, ms, options);

            return(imageId.ToString());
        }
コード例 #10
0
        async Task <Uri> IMessageDataRepository.Put(Stream stream, TimeSpan?timeToLive, CancellationToken cancellationToken)
        {
            var options = BuildGridFsUploadOptions(timeToLive);

            var filename = _fileNameGenerator.GenerateFileName();

            var id = await _bucket.UploadFromStreamAsync(filename, stream, options, cancellationToken)
                     .ConfigureAwait(false);

            LogContext.Debug?.Log("MessageData:Put {Id} {FileName}", id, filename);

            return(_resolver.GetAddress(id));
        }
コード例 #11
0
        public async Task <ObjectId> uploadFileAsync(string fileName, string mimeType, Stream fileStream)
        {
            // var mimeType = sojourner_backend.MimeTypes.GetMimeType(fileName);
            var options = new GridFSUploadOptions()
            {
                Metadata = new ImageMetadata()
                {
                    mimeType = mimeType
                }.ToBsonDocument()
            };

            return(await bucket.UploadFromStreamAsync(fileName, fileStream, options));
        }
コード例 #12
0
        public async Task <IActionResult> Upload(Video p, IFormFile uploadedFile)
        {
            if (ModelState.IsValid)
            {
                await video.InsertOneAsync(p);

                ObjectId fileId = new ObjectId();
                fileId = await gridFS.UploadFromStreamAsync(uploadedFile.FileName, uploadedFile.OpenReadStream());

                p.fileId = fileId.ToString();
                return(RedirectToAction("Index", "HomeController"));
            }
            return(View(p));
        }
コード例 #13
0
 private async Task UploadFileCoreAsync(string id, Stream stream, CancellationToken ct = default)
 {
     try
     {
         await bucket.UploadFromStreamAsync(id, id, stream, cancellationToken : ct);
     }
     catch (MongoWriteException ex) when(ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
     {
         throw new AssetAlreadyExistsException(id);
     }
     catch (MongoBulkWriteException <BsonDocument> ex) when(ex.WriteErrors.Any(x => x.Category == ServerErrorCategory.DuplicateKey))
     {
         throw new AssetAlreadyExistsException(id);
     }
 }
コード例 #14
0
        async Task <Uri> IMessageDataRepository.Put(Stream stream, TimeSpan?timeToLive, CancellationToken cancellationToken)
        {
            var options = BuildGridFsUploadOptions(timeToLive);

            var filename = _fileNameGenerator.GenerateFileName();

            var id = await _bucket.UploadFromStreamAsync(filename, stream, options, cancellationToken)
                     .ConfigureAwait(false);

            if (_log.IsDebugEnabled)
            {
                _log.DebugFormat("MessageData:Put {0} - {1}", id, filename);
            }

            return(_resolver.GetAddress(id));
        }
コード例 #15
0
ファイル: ProductService.cs プロジェクト: mxgvrl/Showcase
        public async Task StoreImage(string id, Stream imageStream, string imageName)
        {
            var p = await GetProduct(id);

            if (p.HasImage())
            {
                await gridFS.DeleteAsync(new ObjectId(p.imageID));
            }
            var imageId = await gridFS.UploadFromStreamAsync(imageName, imageStream);

            p.imageID = imageId.ToString();
            var filter = Builders <Product> .Filter.Eq("_id", new ObjectId(p.Id));

            var update = Builders <Product> .Update.Set("imageID", p.imageID);

            await products.UpdateOneAsync(filter, update);
        }
コード例 #16
0
        public async Task StoreImage(string id, Stream imageStream, string imageName)
        {
            Phone p = await GetPhone(id);

            if (p.HasImage())
            {
                await gridFS.DeleteAsync(new ObjectId(p.ImageId));
            }

            ObjectId imageId = await gridFS.UploadFromStreamAsync(imageName, imageStream);

            p.ImageId = imageId.ToString();
            var filter = Builders <Phone> .Filter.Eq("_id", new ObjectId(p.Id));

            var update = Builders <Phone> .Update.Set("ImageId", p.ImageId);

            await Phones.UpdateOneAsync(filter, update);
        }
コード例 #17
0
        public async Task StoreFile(string id, Stream trackStream, string trackName)
        {
            Track p = await GetTrack(id);

            if (p.HasFile())
            {
                await gridFS.DeleteAsync(new ObjectId(p.FileId));
            }

            ObjectId trackID = await gridFS.UploadFromStreamAsync(trackName, trackStream);

            p.FileId = trackID.ToString();

            var filter = Builders <Track> .Filter.Eq("_id", new ObjectId(p.Id));

            var update = Builders <Track> .Update.Set("FileId", p.FileId);

            await Tracks.UpdateOneAsync(filter, update);
        }
コード例 #18
0
        public async Task <IActionResult> Upload([Bind(Prefix = "Item2")] Video p, IFormFile uploadedFile)
        {
            if (ModelState.IsValid)
            {
                ObjectId fileId = new ObjectId();
                fileId = await gridFS.UploadFromStreamAsync(uploadedFile.FileName, uploadedFile.OpenReadStream());

                p.videoFileId = fileId.ToString();
                await video.InsertOneAsync(p);

                //for updating
                var filter = Builders <TalentShower> .Filter.Eq(x => x.userId, p.videoUploaderId);

                var update = Builders <TalentShower> .Update.Set(x => x.hasFile, true);

                await talentShower.UpdateOneAsync(filter, update);
            }
            return(RedirectToAction("Index", "Home"));
        }
コード例 #19
0
        // сохранение изображения
        public async Task StoreImage(string email, Stream imageStream, string imageName)
        {
            User c = await GetUserE(email);

            if (c.HasImage())
            {
                // если ранее уже была прикреплена картинка, удаляем ее
                await gridFS.DeleteAsync(new ObjectId(c.ImageId));
            }
            // сохраняем изображение
            ObjectId imageId = await gridFS.UploadFromStreamAsync(imageName, imageStream);

            // обновляем данные по документу
            c.ImageId = imageId.ToString();
            var filter = Builders <User> .Filter.Eq("Email", c.Email);

            var update = Builders <User> .Update.Set("ImageId", c.ImageId);

            await Users.UpdateOneAsync(filter, update);
        }
コード例 #20
0
        // сохранение изображения
        public async Task StoreImage(string code, Stream imageStream, string imageName)
        {
            Speciality s = await GetSpecialityCode(code);

            if (s.HasImage())
            {
                await gridFS.DeleteAsync(new ObjectId(s.ImageId));
            }

            // сохраняем изображение
            ObjectId imageId = await gridFS.UploadFromStreamAsync(imageName, imageStream);

            // обновляем данные по документу
            s.ImageId = imageId.ToString();
            var filter = Builders <Speciality> .Filter.Eq("Code", s.Code);

            var update = Builders <Speciality> .Update.Set("ImageId", s.ImageId);

            await Specialities.UpdateOneAsync(filter, update);
        }
コード例 #21
0
        //save image
        public async Task StoreImage(string id, Stream imageStream, string imageName)
        {
            Product p = await GetProduct(id);

            if (p.HasImage())
            {
                //if a picture was already attached earlier, delete it
                await gridFS.DeleteAsync(new ObjectId(p.ImageId));
            }
            // save the image
            ObjectId imageId = await gridFS.UploadFromStreamAsync(imageName, imageStream);

            //updating document data
            p.ImageId = imageId.ToString();
            var filter = Builders <Product> .Filter.Eq("_id", new ObjectId(p.Id));

            var update = Builders <Product> .Update.Set("ImageId", p.ImageId);

            await Products.UpdateOneAsync(filter, update);
        }
コード例 #22
0
        // сохранение изображения
        public async Task StoreImage(string id, Stream imageStream, string imageName)
        {
            ImageWithUrl p = await GetProduct(id);

            if (p.HasImage())
            {
                // если ранее уже была прикреплена картинка, удаляем ее
                await gridFS.DeleteAsync(new ObjectId(p.ImageId));
            }
            // сохраняем изображение
            ObjectId imageId = await gridFS.UploadFromStreamAsync(imageName, imageStream);

            // обновляем данные по документу
            p.ImageId = imageId.ToString();
            var filter = Builders <ImageWithUrl> .Filter.Eq("_id", new ObjectId(p.Id));

            var update = Builders <ImageWithUrl> .Update.Set("ImageId", p.ImageId);

            await imagesWithUrl.UpdateOneAsync(filter, update);
        }
コード例 #23
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);
        }
コード例 #24
0
        public async Task <string> Put(Stream stream, TimeSpan timeToBeReceived)
        {
            var key = await _fs.UploadFromStreamAsync(Guid.NewGuid().ToString(), stream).ConfigureAwait(false);

            return(key.ToString());
        }
コード例 #25
0
 public async Task <ObjectId> StoreLogFile(Stream logFileStream, string logFileName)
 {
     return(await _gridFS.UploadFromStreamAsync(logFileName, logFileStream));
 }
コード例 #26
0
        public async Task <string> StoreImage(Stream imageStream, string imageName)
        {
            ObjectId imageId = await _gridFS.UploadFromStreamAsync(imageName, imageStream);

            return(imageId.ToString());
        }
コード例 #27
0
        public async Task <string> CreateAsync(Stream source, string name)
        {
            var id = await _documents.UploadFromStreamAsync(name, source);

            return(id.ToString());
        }