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()); } }
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); } }
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); } }
/// <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); }
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); } }
/// <inheritdoc /> public async Task <string> StoreFile(string fileName, Stream fileStream) { var objectId = await _bucket.UploadFromStreamAsync( fileName, fileStream); return(objectId.ToString()); }
// сохранение изображения 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)); }
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()); }
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)); }
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)); }
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)); }
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); } }
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)); }
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); }
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); }
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); }
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")); }
// сохранение изображения 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); }
// сохранение изображения 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); }
//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); }
// сохранение изображения 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); }
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); }
public async Task <string> Put(Stream stream, TimeSpan timeToBeReceived) { var key = await _fs.UploadFromStreamAsync(Guid.NewGuid().ToString(), stream).ConfigureAwait(false); return(key.ToString()); }
public async Task <ObjectId> StoreLogFile(Stream logFileStream, string logFileName) { return(await _gridFS.UploadFromStreamAsync(logFileName, logFileStream)); }
public async Task <string> StoreImage(Stream imageStream, string imageName) { ObjectId imageId = await _gridFS.UploadFromStreamAsync(imageName, imageStream); return(imageId.ToString()); }
public async Task <string> CreateAsync(Stream source, string name) { var id = await _documents.UploadFromStreamAsync(name, source); return(id.ToString()); }