public async Task <IActionResult> Handle(string workflowDefinitionId, [FromForm] IFormFile?file, CancellationToken cancellationToken) { if (file == null) { return(BadRequest()); } var json = await file.OpenReadStream().ReadStringToEndAsync(cancellationToken); var workflowDefinition = await _workflowPublisher.GetDraftAsync(workflowDefinitionId, cancellationToken) ?? _workflowPublisher.New(); var postedModel = _contentSerializer.Deserialize <WorkflowDefinition>(json); workflowDefinition.Activities = postedModel.Activities; workflowDefinition.Connections = postedModel.Connections; workflowDefinition.Description = postedModel.Description; workflowDefinition.Name = postedModel.Name; workflowDefinition.Tag = postedModel.Tag; workflowDefinition.Variables = postedModel.Variables; workflowDefinition.ContextOptions = postedModel.ContextOptions; workflowDefinition.CustomAttributes = postedModel.CustomAttributes; workflowDefinition.DisplayName = postedModel.DisplayName; workflowDefinition.IsSingleton = postedModel.IsSingleton; workflowDefinition.DeleteCompletedInstances = postedModel.DeleteCompletedInstances; await _workflowPublisher.SaveDraftAsync(workflowDefinition, cancellationToken); return(Ok(workflowDefinition)); }
public IActionResult DatabaseUpload(IFormFile?files) { using (_context) using (var transaction = _context.Database.BeginTransaction()) { if (files != null) { CsvFileDescription csvFileDescription = new CsvFileDescription { SeparatorChar = ',', FirstLineHasColumnNames = true }; LINQtoCSV.CsvContext csvContext = new LINQtoCSV.CsvContext(); StreamReader streamReader = new StreamReader(files.OpenReadStream()); IEnumerable <Member> list = csvContext.Read <Member>(streamReader, csvFileDescription); //_context.Member.UpdateRange(list); _context.Member.AddRange(list); _context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.TestMembers ON"); _context.SaveChanges(); _context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT dbo.TestMembers OFF"); transaction.Commit(); } } return(Redirect(nameof(Database))); }
public IActionResult SaveChanges(IFormFile?photo, string login, string url, string name, string surname, string oldPassword, string newPassword) { User user = usersTable.GetUserByEmail(User.Identity.Name !) !; UpdateResult result = new UpdateResult(); if (photo != null) { string path = "/img/users-photos/" + photo.FileName; using (var fs = new FileStream(appEnv.WebRootPath + path, FileMode.Create)) { photo.CopyTo(fs); } usersTable.UpdateUserPhoto(user, ".." + path); } result.IsCorrectLogin = UpdateLogin(user, login); result.IsCorrectUrl = UpdateUrl(user, url); result.IsCorrectName = UpdateName(user, name); result.IsCorrectSurname = UpdateSurname(user, surname); if (!string.IsNullOrEmpty(oldPassword) && !string.IsNullOrEmpty(newPassword)) { result.IsCorrectOldPassword = user.Password == oldPassword; if (!result.IsCorrectOldPassword) { return(Json(result)); } result.IsCorrectNewPassword = usersTable.UpdateUserPassword(user, newPassword); } return(Json(result)); }
public async Task <IActionResult> Create(int id, Person person, IFormFile?file) { if (ModelState.IsValid) { person.FamilyTreeId = id; if (file != null) { var fileName = UploadPicture(file); person.Picture = fileName; } else if (person.GenderId == 1) { person.Picture = "female-user-avatar.png"; } else if (person.GenderId == 2) { person.Picture = "male-user-avatar.png"; } _context.Add(person); await _context.SaveChangesAsync(); return(RedirectToAction("PeopleInFamilyTree", "FamilyTrees", new { id })); } var vm = new PersonsViewModel { GenderSelectList = new SelectList(_context.Genders, "GenderId", "Name", person.GenderId) }; return(View(vm)); }
public async Task <IActionResult> UpdateImage([FromRoute] Guid deckId, [Models.Validation.FileExtensions("jpg", "jpeg", "png")] IFormFile?image) { if (!ModelState.IsValid) { return(UnprocessableEntity(ModelState)); } var deck = await deckRepo.FindAsync(deckId); if (deck is null) { return(NotFound()); } if (image is null) { ImageStore.RemoveImage(deck.ImagePath?.Split('/').Last()); deck.ImagePath = null; } else { var oldPath = deck.ImagePath; deck.ImagePath = await ImageStore.SaveImage(image.OpenReadStream(), '.' + image.FileName.Split('.')[1]); ImageStore.RemoveImage(oldPath?.Split('/').Last()); } await deckRepo.UpdateAsync(deck); return(NoContent()); }
/// <summary> /// Produce the notification. /// </summary> /// <param name="context">The HTTP context.</param> /// <param name="id">The target ID.</param> /// <param name="type">The target type.</param> /// <param name="formFile">The form file.</param> internal ImageUploadPermission(HttpContext context, int?id, string?type, IFormFile?formFile) { Context = context; Id = id; Type = type; FormFile = formFile; }
public async Task <IActionResult> Add(RegisterModel model, IFormFile?file) { if (ModelState.IsValid) { AppUser user = new AppUser(); user.Email = model.Email; user.UserName = model.UserName; var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "img", "avatars", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } user.Image = file.FileName; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(RedirectToAction("List")); } else { foreach (var item in result.Errors) { ModelState.AddModelError("", item.Description); } } } return(View(model)); }
public async Task <IActionResult> Edit(int id, Person person, IFormFile?file) { if (id != person.PersonId) { return(NotFound()); } if (ModelState.IsValid) { if (file != null) { var fileName = UploadPicture(file); DeletePicture(person.Picture); person.Picture = fileName; } _context.Persons.Update(person); await _context.SaveChangesAsync(); return(RedirectToAction("PeopleInFamilyTree", "FamilyTrees", new { id = person.FamilyTreeId })); } var vm = new PersonsViewModel { Person = person, GenderSelectList = new SelectList(_context.Genders, "GenderId", "Name", person.GenderId) }; return(View(vm)); }
public static bool UploadImageToServer(IFormFile? formFile, string filePass) { if (formFile == null) return false; using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential("ColdForeign", "SalO123zxcSuper"); try { using (var memoryStream = new MemoryStream()) { formFile.CopyToAsync(memoryStream); if (memoryStream.Length < 2097152) { return client.UploadData(filePass, memoryStream.ToArray()) != null; } else return false; } } catch (Exception ex) { return false; } } }
public static async Task <FileParameter?> ToFileParameter(this IFormFile?file, bool copyStream = false) { if (file == null || file.Length == 0) { return(null); } Stream fileStream; if (copyStream) { MemoryStream memoryStream = new((int)file.Length); await file.CopyToAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); fileStream = memoryStream; } else { fileStream = file.OpenReadStream(); } return(new() { ContentDisposition = file.ContentDisposition, ContentType = file.ContentType, FileName = file.FileName, Length = file.Length, Name = file.Name, InputStream = fileStream, }); }
public async Task <IActionResult> Create(string title, string text, long?id, IFormFile?file) { if (id == null) { return(NotFound()); } if (title == null) { ViewBag.Error = "Title field should be passed"; return(View()); } if (text == null) { ViewBag.Error = "Text field should be passed"; return(View()); } string?path = null; if (file != null) { path = "/attachments/" + file.FileName; await file.CopyToAsync(new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)); } _roomService.CreateRoom(text, title, HttpContext.User.Identity.Name, (long)id, path); return(Redirect("/")); }
public async Task UploadProfileImage(IFormFile?file, CancellationToken cancellationToken) { if (file is null) { throw new BadRequestException(); } var userId = User.GetUserId(); var user = await _userManager.FindByIdAsync(userId.ToString()); if (user is null) { throw new ResourceNotFoundException(); } var profileImageName = Guid.NewGuid().ToString(); await using var fileStream = file.OpenReadStream(); Directory.CreateDirectory(_appSettings.Value.UserProfileImagePath); var path = Path.Combine($"{_appSettings.Value.UserProfileImagePath}\\{profileImageName}{Path.GetExtension(file.FileName)}"); await using var targetStream = SystemFile.Create(path); await fileStream.CopyToAsync(targetStream, cancellationToken); if (user.ProfileImageName is not null) { try { var filePath = Directory.GetFiles(_appSettings.Value.UserProfileImagePath, $"{user.ProfileImageName}.*").FirstOrDefault(); if (filePath != null) { SystemFile.Delete(filePath); } } catch { // not important } } try { user.ProfileImageName = profileImageName; await _userManager.UpdateAsync(user); } catch { SystemFile.Delete(path); throw; } }
public IActionResult CompanyUpdate(Company company, IFormFile?logo) { company.Logo = uploadImages.UploadedImage(logo); CompanyRepository.CompanRep.Update(company); //geçiçi olarak yönlendirme işlemi için eklendi Buraya login olan kullanıcının bilgileri gelicek. return(RedirectToAction("Index", PersonelRepository.PersonelsRepository.GetPersonelByID(1))); }
private static bool CheckFormFileNotNull([NotNullWhen(true)] IFormFile?formFile, ModelStateDictionary?modelState, string fieldName) { if (formFile == null) { modelState?.AddModelError("", string.Format(CultureInfo.InvariantCulture, "{0} is required.", fieldName)); return(false); } return(true); }
public string Upload(IFormFile?formFile) { if (formFile == null) { return("failed"); } Console.WriteLine(formFile.Name); return("success"); }
public UpdateUserCommand(Guid id, string userName, string name, string family, string email, IFormFile?photo) { Id = id; Username = userName; Name = name; Family = family; Email = email; Photo = photo; }
public async Task<ActionResult<Filme>> PostFilme([FromForm]Filme filme, IFormFile? poster) { string caminhoCompleto = ""; bool haImagem = false; if (poster == null) { // não há ficheiro! filme.Poster = "noimage.png"; } else { // há ficheiro. if (poster.ContentType == "image/jpeg" || poster.ContentType == "image/png") { //existe imagem Guid g; g = Guid.NewGuid(); // identificar a Extensão do ficheiro string extensao = Path.GetExtension(poster.FileName).ToLower(); // nome do ficheiro string nome = g.ToString() + extensao; // Identificar o caminho onde o ficheiro vai ser guardado caminhoCompleto = Path.Combine(_path.WebRootPath, "Imagens", nome); // associar o nome da fotografia filme.Poster = nome; // assinalar que existe imagem haImagem = true; } else { filme.Poster = "noimage.png"; } } _context.Filme.Add(filme); await _context.SaveChangesAsync(); if (haImagem) { using var stream = new FileStream(caminhoCompleto, FileMode.Create); await poster.CopyToAsync(stream); } return CreatedAtAction("GetFilme", new { id = filme.Id }, filme); }
public async Task <IActionResult> Product(ProductView product, IFormFile?formFile) { ViewBag.Brands = new List <Brand>(); ViewBag.Sections = new List <Section>(); if (ModelState.IsValid) { if (product.Id != -1) { var productDB = _sqlProductData.GetProductById(product.Id); productDB.Name = product.Name; productDB.Order = product.Order; productDB.Price = product.Price; productDB.ImageUrl = formFile?.FileName ?? product.ImageUrl; productDB.BrandId = product.BrandId; productDB.SectionId = product.SectionId; } else { var productNew = new Product() { Name = product.Name, Order = product.Order, Price = product.Price, ImageUrl = formFile?.FileName ?? product.ImageUrl, BrandId = product.BrandId, SectionId = product.SectionId }; _sqlProductData.CreateProduct(productNew); } if (formFile != null) { var path = "/images/shop/" + formFile.FileName; using (var fs = new FileStream(_environment.WebRootPath + path, FileMode.Create)) { await formFile.CopyToAsync(fs); } } _sqlProductData.SaveDB(); return(RedirectToAction("Products", "ShopElemet", new { area = "Admin" })); } var brands = _sqlProductData.GetBrands(); ViewBag.Brands = new SelectList(brands, "Id", "Name"); var sections = _sqlProductData.GetSections(); ViewBag.Sections = new SelectList(sections, "Id", "Name"); return(View(product)); }
public async Task <IActionResult> AddDiscuss(long id, string text, IFormFile?file) { string?path = null; if (file != null) { path = "/attachments/" + file.FileName; await file.CopyToAsync(new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)); } _discussionService.AddDiscussion(text, HttpContext.User.Identity.Name, id, path); return(Redirect($"/Room/Detail/{id}")); }
public IActionResult UserUpdate(Personel personel, IFormFile?profilPicUrl) { Personel updatedPersonel = PersonelRepository.PersonelsRepository.GetPersonelByID(1); updatedPersonel.FirstName = personel.FirstName; updatedPersonel.LastName = personel.LastName; updatedPersonel.ProfilPicUrl = uploadImages.UploadedImage(profilPicUrl); PersonelRepository.PersonelsRepository.Update(updatedPersonel); //geçiçi olarak yönlendirme işlemi için eklendi Buraya login olan kullanıcının bilgileri gelicek. return(RedirectToAction("Index", PersonelRepository.PersonelsRepository.GetPersonelByID(personel.ID))); }
/// <summary> /// Validates and parses a FormFile into an Image, adding any errors into modelState. /// </summary> /// <param name="formFile">The uploaded Http file.</param> /// <param name="modelState">The view ModelState containing errors.</param> /// <param name="fieldName">The display name of field to display in errors.</param> /// <param name="maxFileSizeMb">The maximum file size in MB, or null.</param> /// <returns>The image if FormFile is valid, otherwise null.</returns> public async Task <Image <Rgba32>?> ProcessAsImageAsync(IFormFile?formFile, ModelStateDictionary?modelState = null, string fieldName = "Image", int?maxFileSizeMb = null) { modelState.CheckNotNull(nameof(modelState)); if (maxFileSizeMb != null && maxFileSizeMb <= 0) { throw new ArgumentOutOfRangeException(string.Format(CultureInfo.InvariantCulture, Res.ValueMustBeNullOrPositive, nameof(maxFileSizeMb))); } if (formFile == null) { modelState?.AddModelError("", string.Format(CultureInfo.InvariantCulture, Res.FieldRequired, fieldName)); return(null); } var fileName = Path.GetFileName(formFile.FileName); if (formFile.Length == 0) { modelState?.AddModelError(formFile.Name, string.Format(CultureInfo.InvariantCulture, Res.FileIsEmpty, fieldName, fileName)); } else if (formFile.Length > maxFileSizeMb * 1024 * 1024) { modelState?.AddModelError(formFile.Name, string.Format(CultureInfo.InvariantCulture, Res.FileExceedsMaxSize, fieldName, fileName, maxFileSizeMb)); } else { // Check file extension (must be JPG, GIF or PNG). if (fileName == null || !ValidExtensions.Any(x => fileName.EndsWith(x, StringComparison.InvariantCultureIgnoreCase))) { modelState?.AddModelError(formFile.Name, string.Format(CultureInfo.InvariantCulture, Res.FileIsNotValidImage, fieldName, fileName)); } else { // Ensure file is valid. try { var result = await Task.Run(() => Image.Load(formFile.OpenReadStream())).ConfigureAwait(false); return(result); } catch (NotSupportedException) { modelState?.AddModelError(formFile.Name, string.Format(CultureInfo.InvariantCulture, Res.FileIsNotValidImage, fieldName, fileName)); } } } return(null); }
private UploadAppImage CreateCommand(IFormFile?file) { if (file == null || Request.Form.Files.Count != 1) { var error = new ValidationError($"Can only upload one file, found {Request.Form.Files.Count} files."); throw new ValidationException("Cannot upload image.", error); } return(new UploadAppImage { File = file.ToAssetFile() }); }
private UploadAppImage CreateCommand(IFormFile?file) { if (file == null || Request.Form.Files.Count != 1) { var error = T.Get("validation.onlyOneFile"); throw new ValidationException(error); } return(new UploadAppImage { File = file.ToAssetFile() }); }
BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext is null) { throw new ArgumentNullException(nameof(controllerContext)); } if (bindingContext is null) { throw new ArgumentNullException(nameof(bindingContext)); } IFormFile?theFile = controllerContext.HttpContext.Request.Form.Files.GetFile(bindingContext.ModelName); return(ChooseFileOrNull(theFile)); }
public async Task <IActionResult> ReplacePicture(int brotherId, [FromForm] IFormFile?picture) { string? subjectId = _principal.GetSubjectId(); Brother brother = await _dbContext.Brother.FindBrotherByIdAsync(brotherId); if (brother == null) { _logger.LogInformation("Received request to modify picture for brother {id} but they do not exist.", brotherId); return(NotFound()); } _logger.LogInformation("Received request to modify picture for brother {brotherId} ({first} {last}).", brotherId, brother.FirstName, brother.LastName); // TODO: The subject id is not necessarily the same as the brother id. They should be linked by a column in the Brother table that does not yet exist. IEnumerable <string> scopes = _principal.GetScopes(); if (!brotherId.ToString().Equals(subjectId, StringComparison.OrdinalIgnoreCase)) { if (!scopes.Contains(Constants.Scopes.Administrator)) { _logger.LogTrace("Rejecting request to modify another user's picture from non-administrator user {subject}.", subjectId); return(Unauthorized()); } // User is an administrator _logger.LogTrace("Administrator replacing picture for {brother}.", brotherId); } if (picture == null || picture.Length == 0) { _logger.LogTrace("Clearing picture."); brother.Picture = null; } else { brother.Picture = new byte[picture.Length]; await picture.OpenReadStream().ReadAsync(brother.Picture, 0, (int)picture.Length); } try { await _dbContext.SaveChangesAsync(); } catch (DBConcurrencyException) { return(Conflict()); } return(Ok()); }
public static FileUploadCommand Create(IFormFile?formFile, FileUploadDto mediaDto, string?authorId) { if (formFile == null) { throw new ArgumentNullException(nameof(formFile)); } if (mediaDto == null) { throw new ArgumentNullException(nameof(mediaDto)); } if (mediaDto.Tags == null) { throw new ArgumentNullException(nameof(mediaDto.Tags)); } return(new FileUploadCommand(formFile, mediaDto, authorId)); }
/// <summary> /// Uploads a file stream to the server. /// </summary> /// <param name="formFile">The FormFile containing the file.</param> /// <param name="modelState">The view ModelState containing errors.</param> /// <param name="uploadDirectory">The directory in which to store the file.</param> /// <param name="destFileName">The destination file name.</param> /// <param name="modelState">The view ModelState containing errors.</param> /// <param name="fieldName">The display name of field to display in errors.</param> public async Task UploadFileAsync(IFormFile?formFile, string uploadDirectory, string destFileName, ModelStateDictionary?modelState = null, string fieldName = "") { fieldName = fieldName.Default("File"); destFileName.CheckNotNullOrEmpty(nameof(destFileName)); if (!CheckFormFileNotNull(formFile, modelState, fieldName) || formFile == null) { return; } // suppress warning below // Save image in upload folder. var filePath = GetFilePathAbsolute(uploadDirectory, destFileName); using var outStream = _fileSystem.CreateFileStream(filePath); using var inStream = formFile.OpenReadStream(); await inStream.CopyToAsync(outStream).ConfigureAwait(false); }
ChooseFileOrNull(IFormFile?rawFile) { // case 1: there was no <input type="file" ... /> element in the post if (rawFile is null) { return(null); } // case 2: there was an <input type="file" ... /> element in the post, but it was left blank if (rawFile.Length == 0 && String.IsNullOrEmpty(rawFile.FileName)) { return(null); } // case 3: the file was posted return(rawFile); }
/// <summary> /// Uploads an image file to the server. /// </summary> /// <param name="formFile">The FormFile containing the picture.</param> /// <param name="uploadDirectory">The directory in which to store the file.</param> /// <param name="destFileNameWithoutExt">The destination file name without extension.</param> /// <param name="destFileFormat">The image file format extension to save, or null to keep the original image format.</param> /// <param name="modelState">The view ModelState containing errors.</param> /// <param name="fieldName">The display name of field to display in errors.</param> /// <param name="transform">A function to transform the image before saving.</param> /// <returns>The file name where the image was saved, or null.</returns> public async Task <string?> UploadImageAsync(IFormFile?formFile, string uploadDirectory, string destFileNameWithoutExt, string?destFileFormat = null, ModelStateDictionary?modelState = null, string fieldName = "", Func <Image <Rgba32>, Task>?transform = null) { fieldName = fieldName.Default("File"); if (!CheckFormFileNotNull(formFile, modelState, fieldName) || formFile == null) { return(null); } // suppress warning below var upload = await ProcessAsImageAsync(formFile, modelState).ConfigureAwait(false); if (upload != null) { destFileFormat = string.IsNullOrEmpty(destFileFormat) ? Path.GetExtension(formFile.FileName) : destFileFormat; return(await SaveImageAsync(upload, uploadDirectory, destFileNameWithoutExt, destFileFormat, transform).ConfigureAwait(false)); } return(null); }
/// <summary> /// ProcessFormFileAsync /// </summary> /// <param name="formFile"></param> /// <param name="permittedFileSuffixes"></param> /// <param name="sizeLimit"></param> /// <returns></returns> /// <exception cref="ApiException"></exception> public async Task <byte[]> ProcessFormFileAsync(IFormFile?formFile, string[] permittedFileSuffixes, long sizeLimit) { // Check the file length. This check doesn't catch files that only have // a BOM as their content. if (formFile == null || formFile.Length == 0 || permittedFileSuffixes.IsNullOrEmpty()) { throw ApiExceptions.ApiUploadEmptyFile(); } if (formFile.Length > sizeLimit) { throw ApiExceptions.ApiUploadOverSize(); } try { using MemoryStream memoryStream = new MemoryStream(); await formFile.CopyToAsync(memoryStream).ConfigureAwait(false); // Check the content length in case the file's only // content was a BOM and the content is actually // empty after removing the BOM. if (memoryStream.Length == 0) { throw ApiExceptions.ApiUploadEmptyFile(); } if (!IsValidFileExtensionAndSignature( formFile.FileName, memoryStream, permittedFileSuffixes)) { throw ApiExceptions.ApiUploadWrongType(); } else { return(memoryStream.ToArray()); } } catch (Exception ex) { throw ApiExceptions.ServerUnkownError(fileName: formFile.FileName, innerException: ex); } }