public async Task <ActionResultReponese <List <FileViewModel> > > UploadFiles(string FileCode, string FileName, string creatorId, string FolderName, int?folderId, IFormFileCollection formFileCollection) { List <Files> listFiles = new List <Files>(); string uploadUrl = string.Format("/uploads/" + FolderName + "/{0:yyyy/MM/dd}/", DateTime.Now); Folder folderInfo = null; if (folderId.HasValue) { folderInfo = await _folderRepository.GetInfoAsync(folderId.Value); if (folderInfo == null) { return(new ActionResultReponese <List <FileViewModel> >(-1, "Folder does not exists. You can not update file to this folder.")); } //_ghmFileResource.GetString("Folder does not exists. You can not update file to this folder.")); } foreach (IFormFile formFile in formFileCollection) { var id = Guid.NewGuid().ToString("n"); string urlOutPut = $"{uploadUrl}{id}.{formFile.GetExtensionFile()}"; string uploadPath = $"{CreateFolder()}{id}.{formFile.GetExtensionFile()}"; string uploadPathBackup = $"{CreateFolderBackUp()}{id}.{formFile.GetExtensionFile()}"; var type = formFile.GetTypeFile(); var isImage = type.Contains("image/"); var isNameExit = await _fileRepository.CheckExistsByFolderIdName(id, folderId, formFile.FileName?.Trim()); if (isNameExit) { continue; } await CopyFileToServer(formFile, uploadPathBackup, isImage); var resultCopyFile = await CopyFileToServer(formFile, uploadPath, isImage); if (resultCopyFile == -1) { continue; } var file = new Files { Id = id, FileCode = FileCode, FileName = formFile.FileName?.Trim().StripVietnameseChars().ToUpper(), Type = formFile.GetTypeFile(), Size = formFile.GetFileSize(), Url = urlOutPut, CreatorId = creatorId, Folderld = folderInfo.FolderId, CreateDate = DateTime.Now, DeleteTime = null, LastUpdate = null, IsActive = true, IsDelete = false }; // Add file info to list for insert into database. await _fileRepository.InsertAsync(file); listFiles.Add(file); } return(new ActionResultReponese <List <FileViewModel> > { Code = 1, Message = "Upload file successful", Data = listFiles.Select(x => new FileViewModel { IdFile = x.Id, FileName = x.FileName, FolderId = x.Folderld, Size = x.Size, Type = x.Type, Url = x.Url, CreateDate = x.CreateDate, CreatorId = x.CreatorId, }).ToList() }); string CreateFolder() { var mapPath = string.Format(_webHostEnvironment.ContentRootPath + uploadUrl); if (!Directory.Exists(mapPath)) { Directory.CreateDirectory(mapPath); } return(mapPath); } string CreateFolderBackUp() { var mapPath = string.Format("D:/BackUp" + uploadUrl); if (!Directory.Exists(mapPath)) { Directory.CreateDirectory(mapPath); } return(mapPath); } async Task <int> CopyFileToServer(IFormFile file, string uploadPath, bool isImage = false) { if (System.IO.File.Exists(uploadPath)) { return(-1); } using (var stream = new FileStream(uploadPath, FileMode.Create)) { await file.CopyToAsync(stream); } return(1); } }