public async Task <IActionResult> Create(FileCreateViewModel vm, string categoryLessonId, int uniCategoryId, int depCategoryId) { int userid = Convert.ToInt32(HttpContext.Session.GetInt32("UserId")); var categoryid = Convert.ToInt32(categoryLessonId); var ctrgCourseName = await _context.CategoryTable.FirstOrDefaultAsync(p => p.Id == categoryid); var ctrgUni = await _context.CategoryTable.FirstOrDefaultAsync(p => p.Id == uniCategoryId); var ctrgDep = await _context.CategoryTable.FirstOrDefaultAsync(p => p.Id == depCategoryId); var usr = await _context.UserTable.FirstOrDefaultAsync(p => p.Id == userid); if (vm.FilePath == null || vm.Title == null || categoryid == 0 || uniCategoryId == 0 || depCategoryId == 0 || usr == null) { return(Json(new { ok = false })); } else { File file = new File(); file.CourseName = ctrgCourseName.Name; file.Title = vm.Title; file.Description = vm.Description; file.FilePath = vm.FilePath; file.AddedUser = usr; file.UploadDate = DateTime.Now; file.Category = ctrgCourseName; file.University = ctrgUni.Name; file.Department = ctrgDep.Name; _context.Add(file); await _context.SaveChangesAsync(); return(Json(new { ok = true })); } }
public ActionResult Create(FileCreateViewModel model) { if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { var fileName = this.Request.Files[0].FileName; var extension = Path.GetExtension(fileName); model.File.FileName = String.Format("{0}{1}", Guid.NewGuid(), extension); //delete the old file if (!model.File.IsNew()) { var oldFile = _service.Dal.FileProvider.Get().Single(i => i.Id == model.File.Id).FileName; var oldFilePath = this.Server.MapPath(String.Format("~/user_files/{0}", oldFile)); if (System.IO.File.Exists(oldFilePath)) { System.IO.File.Delete(oldFilePath); } } var saveTo = this.Server.MapPath(String.Format("~/user_files/{0}", model.File.NameWithExtension())); this.Request.Files[0].SaveAs(saveTo); } _service.Dal.FileProvider.Save(model.File); TempData["message"] = "File Saved"; return(RedirectToAction("List", new { id = model.NavigationModel.Page.PageNavigation.Id })); }
public IActionResult Create(FileCreateViewModel file) { if (ModelState.IsValid) { string uniqueFileName = null; if (file.File != null) { // The image must be uploaded to the images folder in wwwroot // To get the path of the wwwroot folder we are using the inject // HostingEnvironment service provided by ASP.NET Core string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "texts"); uniqueFileName = Guid.NewGuid().ToString() + "_" + file.File.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); // Use CopyTo() method provided by IFormFile interface to // copy the file to wwwroot/images folder file.File.CopyTo(new FileStream(filePath, FileMode.Create)); } File file1 = new File { Name = file.Name, FilePath = uniqueFileName }; File newFile = file1; _fileRepository.Add(newFile); return(RedirectToAction("details", new { id = newFile.Id })); } return(View()); }
public ActionResult Create(int pageId, int?id) { var file = id.HasValue ? _service.Dal.FileProvider.Get().Single(i => i.Id == id.Value) : new EKFile { }; var model = new FileCreateViewModel { File = file }; model.NavigationModel = HomeIndexViewModelLoader.Create(pageId, _service); return(View(model)); }
public async Task <ActionResult> UploadFile(FileCreateViewModel model) { if (!ModelState.IsValid) { return(Json(ModelState.ToDictionary())); } var createdFile = await _filesManager.Create(model, User.Identity.GetUserId()); return(Json(createdFile)); }
public async Task <IActionResult> Create(FileCreateViewModel vm) { if (ModelState.IsValid) { var file = vm.ToFile(Storage); DbContext.Add(file); await DbContext.SaveChangesAsync().ConfigureAwait(false); return(RedirectToAction(nameof(Index))); } AddEntityListsToViewBag(); return(View(vm)); }
public IActionResult CreateFile() { var fileName = $"File_{DateTime.Now.Ticks}.txt"; var fileContent = $"Current time is {DateTime.Now.ToLongDateString()}"; var filePath = $"/files/{fileName}"; using (var fs = System.IO.File.Create(filePath)) { var content = Encoding.UTF8.GetBytes(fileContent); fs.Write(content, 0, content.Length); } var result = new FileCreateViewModel { FileName = fileName, IsSuccess = true }; return(RedirectToAction("Create", "Home", result)); }
public IActionResult Create(FileCreateViewModel model) { return(View(model)); }
public async Task <FileListViewModel> Create(FileCreateViewModel model, string agentId) { if (string.IsNullOrEmpty(agentId)) { throw new NotAuthorizedUserException("Само потребители могат да качват файлове!"); } if (!await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Administrator)) && !await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Agent)) && !await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Maintenance))) { throw new NotAuthorizedUserException("Нямате право да извършвате това действие!"); } if (await Exist(fileName: model.Name, folderId: model.FolderId)) { throw new ArgumentException("Съществува файл с това име в тази папка!"); } string filePath = Path.GetFileNameWithoutExtension(model.Name) + Path.GetExtension(model.File.FileName); if (model.FolderId != null) { filePath = Path.Combine(await _dbContext.Folders .Where(f => f.Id == model.FolderId).Select(f => f.RelativePath) .FirstOrDefaultAsync() ?? "", filePath); } else { filePath = Path.Combine(_baseMaterialsPath, filePath); } var physicalFilePath = Path.Combine(HttpRuntime.AppDomainAppPath.TrimEnd('\\'), filePath.Replace('/', '\\').TrimStart('\\')); try { model.File.SaveAs(physicalFilePath); } catch (Exception) { Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath) ?? throw new ArgumentException("Пътят е грешен")); model.File.SaveAs(physicalFilePath); } var file = new Files { Name = Path.GetFileName(filePath), FolderId = model.FolderId, AgentId = agentId, SizeInBytes = model.File.ContentLength, Type = MimeMapping.GetMimeMapping(model.File.FileName), RelativePath = filePath }; try { _dbContext.Files.Add(file); await _dbContext.SaveChangesAsync(); } catch (Exception) { File.Delete(physicalFilePath); throw; } var createdFile = await Get(file.Id, agentId); #region Notifications var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Material, NotificationPicture = "", NotificationLink = "/agentmaterials/index?fileId=" + createdFile.Id + (createdFile.FolderId != null ? "&folderId=" + createdFile.FolderId : ""), NotificationText = createdFile.AgentName + " добави материал: " + createdFile.Name }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, agentId); #endregion return(createdFile); }