public IHttpActionResult ChangeTrashedStatus(string folderId, [FromBody] bool trashed) { FolderManage trashedFolder = null; using (var db = new WebDiskDBEntities()) { string rootId = db.FolderManage.Where(x => x.ParentId == null).SingleOrDefault().FolderId; #region 루트 폴더는 상태 처리 예외 if (folderId != rootId) { trashedFolder = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault(); trashedFolder.Trashed = trashed; if (trashedFolder.Trashed == true) { trashedFolder.Starred = false; } trashedFolder.LastModified = DateTime.Now; db.SaveChanges(); } #endregion } return(Ok(trashedFolder)); }
public IHttpActionResult DeleteFolderAutoForever() { using (var db = new WebDiskDBEntities()) { #region 삭제 대상 폴더 얻기 //스케줄러가 이 API를 호출한다. //휴지통에 있는 파일과 폴더 중에서 t상태가 trashed이고 마지막으로 수정한 날짜에서 두달되는 날인 파일과 폴더를 가져온다. List <FolderManage> deletedFolders = db.FolderManage.Where(x => x.Trashed == true && x.LastModified.Value.Day == DateTime.Now.Day).ToList(); //List<FileManage> deletedFiles = db.FileManage.Where(x => x.Trashed == true && x.LastModified.Value.AddMonths(2) == DateTime.Today).ToList(); //파일이나 폴더를 완전 삭제한다. foreach (var folder in deletedFolders) { DeleteFolder(folder.FolderId); } //foreach(var file in deletedFiles) //{ //} #endregion } return(Ok(new { msg = "OK" })); }
public IHttpActionResult ChangeTrashedStatus(string fileId, [FromBody] bool trashed) { string userId = HttpContext.Current.User.Identity.Name; FileManage file = null; using (var db = new WebDiskDBEntities()) { file = db.FileManage.Where(x => x.FileId == fileId && x.OwnerId == userId).SingleOrDefault(); if (file != null) { file.Trashed = trashed; if (file.Starred == true) { file.Starred = false; //만약 삭제된 파일이 중요처리가 되어 있다면 false처리 } file.LastModified = DateTime.Now; db.SaveChanges(); } else { return(NotFound()); } } return(Ok(file)); }
public IHttpActionResult MoveFolder(string folderId, [FromBody] string targetFolderId) { using (var db = new WebDiskDBEntities()) { string rootId = db.FolderManage.Where(x => x.ParentId == null).SingleOrDefault().FolderId; if (folderId != rootId) { FolderManage sourceFolder = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault(); FolderManage targetFolder = db.FolderManage.Where(x => x.FolderId == targetFolderId).SingleOrDefault(); if (string.IsNullOrEmpty(targetFolder.OwnerId)) { targetFolder.OwnerId = sourceFolder.OwnerId; } string sourPath = Path.Combine(sourceFolder.ServerPath, sourceFolder.OwnerId, sourceFolder.RealPath); string tarPath = Path.Combine(targetFolder.ServerPath, targetFolder.OwnerId, targetFolder.RealPath, sourceFolder.FolderName); //루트로 옮길경우 여기서 에러남 if (!Directory.Exists(tarPath)) { Directory.CreateDirectory(tarPath); } MoveFolderRecursive(folderId, tarPath); Directory.Delete(sourPath); sourceFolder.RealPath = Path.Combine(targetFolder.RealPath, sourceFolder.FolderName); sourceFolder.ParentId = targetFolder.FolderId; db.SaveChanges(); } } return(Ok(new { msg = "OK" })); }
public IHttpActionResult DeleteFileForever(string fileId) { string userId = HttpContext.Current.User.Identity.Name; FileManage deletedFile = null; using (var db = new WebDiskDBEntities()) { deletedFile = db.FileManage.Where(x => x.OwnerId == userId && x.Trashed == true && x.FileId == fileId).SingleOrDefault(); string fileName = deletedFile.FileName + '.' + deletedFile.FileExtension; string fileFullPath = Path.Combine(deletedFile.ServerPath, deletedFile.OwnerId, deletedFile.RealPath, fileName); if (deletedFile != null) { if (File.Exists(fileFullPath)) { File.Delete(fileFullPath); } db.FileManage.Remove(deletedFile); db.SaveChanges(); } else { return(NotFound()); } } return(Ok(deletedFile)); }
public IHttpActionResult RenameFile(string fileId, [FromBody] string newFileName) { string userId = HttpContext.Current.User.Identity.Name; FileManage renamedFile = null; using (var db = new WebDiskDBEntities()) { renamedFile = db.FileManage.Where(x => x.OwnerId == userId && x.FileId == fileId).SingleOrDefault(); //실제 파일 이름도 변경하기 string folderPath = Path.Combine(renamedFile.ServerPath, renamedFile.OwnerId, renamedFile.RealPath); string sourceFilePath = Path.Combine(folderPath, renamedFile.FileName + "." + renamedFile.FileExtension); string targetFilePath = Path.Combine(folderPath, newFileName + "." + renamedFile.FileExtension); if (renamedFile != null) { if (!File.Exists(targetFilePath)) { File.Move(sourceFilePath, targetFilePath); } renamedFile.FileName = newFileName; renamedFile.LastModified = DateTime.Now; db.SaveChanges(); } else { return(NotFound()); } } return(Ok(renamedFile)); }
public HttpResponseMessage DownloadFile(string fileId) { using (var db = new WebDiskDBEntities()) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); FileManage file = db.FileManage.Where(x => x.FileId == fileId).SingleOrDefault(); string fileName = file.FileName + '.' + file.FileExtension; string filePath = Path.Combine(file.ServerPath, file.OwnerId, file.RealPath, file.FileName + '.' + file.FileExtension); if (!File.Exists(filePath)) { //만약 파일이 없으면 404 (Not Found) 에러 response.StatusCode = HttpStatusCode.NotFound; response.ReasonPhrase = string.Format("File not found: {0} .", fileName); throw new HttpResponseException(response); } byte[] bytes = File.ReadAllBytes(filePath); response.Content = new ByteArrayContent(bytes); response.Content.Headers.ContentLength = bytes.LongLength; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName)); return(response); } }
/// <summary> /// 중첩된 폴더 트리 구조를 만드는 재귀 메소드 /// </summary> /// <param name="folderId">해당 폴더 아이디</param> /// <returns></returns> public List <FolderTree> GetFolderTree(string folderId) { List <FolderTree> folderTreeList = new List <FolderTree>(); using (var db = new WebDiskDBEntities()) { List <FolderManage> subFolders = db.FolderManage.Where(x => x.ParentId == folderId && x.Trashed == false).ToList(); if (subFolders.Count > 0) { foreach (var subFolder in subFolders) { FolderTree folderTree = new FolderTree() { FolderId = subFolder.FolderId, FolderName = subFolder.FolderName, Path = subFolder.RealPath, Subfoldercnt = db.FolderManage.Where(x => x.ParentId == subFolder.FolderId).Count(), children = GetFolderTree(subFolder.FolderId) }; folderTreeList.Add(folderTree); } } } return(folderTreeList); }
/// <summary> /// 폴더의 folderId를 Parameter로 받아 폴더 및 하위 폴더와 파일을 찾아 DB에서 삭제한다. /// 호출자는 DeleteFolderForever, DeleteFolderAutoForever 메소드 /// </summary> /// <param name="folderId">해당 폴더 아이디</param> public void DeleteFolder(string folderId) { using (var db = new WebDiskDBEntities()) { List <FolderManage> subfolders = db.FolderManage.Where(x => x.Trashed == true && x.ParentId == folderId).ToList(); List <FileManage> subFiles = db.FileManage.Where(x => x.Trashed == true && x.FolderId == folderId).ToList(); FolderManage currentFolder = db.FolderManage.Where(x => x.Trashed == true && x.FolderId == folderId).SingleOrDefault(); string rootId = db.FolderManage.Where(x => x.ParentId == null).SingleOrDefault().FolderId; if (currentFolder != null && rootId != currentFolder.FolderId) { string folderPath = Path.Combine(currentFolder.ServerPath, currentFolder.OwnerId, currentFolder.RealPath); #region 하위 파일 삭제 //하위 파일 if (subFiles.Count > 0) { for (int i = 0; i < subFiles.Count; i++) { if (subFiles[i] != null) { string fileName = subFiles[i].FileName + '.' + subFiles[i].FileExtension; string filePath = Path.Combine(subFiles[i].ServerPath, subFiles[i].OwnerId, subFiles[i].RealPath, fileName); if (File.Exists(filePath)) { File.Delete(filePath); } db.FileManage.Remove(subFiles[i]); db.SaveChanges(); } } } #endregion if (subfolders.Count > 0) { #region 하위 폴더 삭제하기 for (int i = 0; i < subfolders.Count; i++) { if (subfolders[i] != null) { //재귀함수 호출 DeleteFolder(subfolders[i].FolderId); } } #endregion } #region 현재 폴더 삭제하기 Directory.Delete(folderPath); db.FolderManage.Remove(currentFolder); db.SaveChanges(); #endregion } } }
public IHttpActionResult SearchFiles(string q) { string userId = HttpContext.Current.User.Identity.Name; List <FileManage> searchResults = null; using (var db = new WebDiskDBEntities()) { searchResults = db.FileManage.Where(x => x.FileName.Contains(q) && x.Trashed == false && x.OwnerId == userId).ToList(); } return(Ok(searchResults)); }
public IHttpActionResult DeleteFolderForever(string folderId) { using (var db = new WebDiskDBEntities()) { #region 폴더 삭제 재귀함수 호출 DeleteFolder(folderId); #endregion } return(Ok(new { msg = "OK" })); }
public IHttpActionResult CopyFolder(string folderId, [FromBody] string targetFolderId) { using (var db = new WebDiskDBEntities()) { string rootId = db.FolderManage.Where(x => x.ParentId == null).SingleOrDefault().FolderId; if (folderId != rootId) { CopyFolderRecursive(folderId, targetFolderId); } } return(Ok(new { msg = "OK" })); }
public IHttpActionResult GetTrashedDisk() { List <FolderManage> folderList = null; List <FileManage> fileList = null; Folder trashedDisk = new Folder(); using (var db = new WebDiskDBEntities()) { folderList = db.FolderManage.Where(x => x.Trashed == true && x.OwnerId == HttpContext.Current.User.Identity.Name).OrderByDescending(o => o.CreatedDate).ToList(); fileList = db.FileManage.Where(x => x.Trashed == true && x.OwnerId == HttpContext.Current.User.Identity.Name).OrderByDescending(o => o.CreatedDate).ToList(); trashedDisk.subFolders = folderList; trashedDisk.subFiles = fileList; } return(Ok(trashedDisk)); }
public IHttpActionResult GetStarredDisk() { List <FolderManage> folderList = null; List <FileManage> fileList = null; Folder folder = new Folder(); using (var db = new WebDiskDBEntities()) { folderList = db.FolderManage.Where(x => x.Starred == true).OrderByDescending(o => o.CreatedDate).ToList(); fileList = db.FileManage.Where(x => x.Starred == true).OrderByDescending(o => o.CreatedDate).ToList(); folder.subFolders = folderList; folder.subFiles = fileList; } return(Ok(folder)); }
public IHttpActionResult Authenticate([FromBody] Users users) { using (var db = new WebDiskDBEntities()) { Users user = db.Users.SingleOrDefault(x => x.Email == users.Email && x.Password == users.Password); if (user != null) { string userRole = Enum.GetName(typeof(WebDiskApplication.Manage.Enums.UserRole), user.UserRole); string accessToken = createToken(user.UserId, userRole); return(Ok(new { accessToken = accessToken })); } else { return(Unauthorized()); } } }
public IHttpActionResult GetFolderTreePath() { FolderTree folderTree = new FolderTree(); using (var db = new WebDiskDBEntities()) { //루트 폴더 가져오기 FolderManage rootFolder = db.FolderManage.Where(x => x.ParentId == null).SingleOrDefault(); folderTree.FolderId = rootFolder.FolderId; folderTree.FolderName = rootFolder.FolderName; folderTree.Subfoldercnt = db.FolderManage.Where(x => x.ParentId == rootFolder.FolderId && x.Trashed == false).Count(); folderTree.Path = rootFolder.RealPath; folderTree.children = GetFolderTree(rootFolder.FolderId); //GetFolderTree 재귀 메서드 호출 } return(Ok(folderTree)); }
/// <summary> /// 폴더의 path를 생성하는 재귀메소드 /// </summary> /// <param name="folderId"></param> /// <param name="routes"></param> /// <returns></returns> public List <FolderInfo> getPath(string folderId, List <FolderInfo> routes = null) { FolderManage currentFolder = null; FolderManage parentFolder = null; List <FolderInfo> routeList; if (routes != null) { routeList = routes.ToList(); } else { routeList = new List <FolderInfo>(); } using (var db = new WebDiskDBEntities()) { currentFolder = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault(); if (routeList.Count == 0) { routeList.Add(new FolderInfo { folderId = currentFolder.FolderId, folderName = currentFolder.FolderName }); } parentFolder = db.FolderManage.Where(x => x.FolderId == currentFolder.ParentId).SingleOrDefault(); if (parentFolder == null) { return(routeList); } routeList.Add(new FolderInfo { folderId = parentFolder.FolderId, folderName = parentFolder.FolderName }); }; return(getPath(parentFolder.FolderId, routeList)); }
public IHttpActionResult MoveFileToTargetFolder(string fileId, [FromBody] string targetFolderId) { FileManage sourceFile = null; string userId = HttpContext.Current.User.Identity.Name; using (var db = new WebDiskDBEntities()) { sourceFile = db.FileManage.Where(x => x.FileId == fileId).SingleOrDefault(); if (sourceFile != null) { FolderManage targetFolder = db.FolderManage.Where(x => x.FolderId == targetFolderId).SingleOrDefault(); string fullFileName = sourceFile.FileName + "." + sourceFile.FileExtension; string commonPath = Path.Combine(sourceFile.ServerPath, sourceFile.OwnerId); string sourceFilePath = Path.Combine(commonPath, sourceFile.RealPath, fullFileName); string targetFilePath = Path.Combine(commonPath, targetFolder.RealPath, fullFileName); if (sourceFilePath != targetFilePath) { if (File.Exists(targetFilePath)) //만약 타겟 폴더에 똑같은 파일이 있으면 { File.Delete(sourceFilePath); //기존 폴더에 있는 파일은 지운다. } else { File.Move(sourceFilePath, targetFilePath); //만약에 타겟폴더에 해당 파일이 없으면 이동시킨다. } //DB에 저장하기 sourceFile.FolderId = targetFolderId; sourceFile.RealPath = targetFolder.RealPath; db.SaveChanges(); } } else { return(NotFound()); } } return(Ok(sourceFile)); }
public IHttpActionResult RenameFolder(string folderId, [FromBody] string newFolderName) { FolderManage renamedfolder = null; string userId = HttpContext.Current.User.Identity.Name; using (var db = new WebDiskDBEntities()) { renamedfolder = db.FolderManage.Where(x => x.FolderId == folderId && x.OwnerId == userId).SingleOrDefault(); string serverPath = renamedfolder.ServerPath; //서버 path string realPath = renamedfolder.RealPath; // 원본 폴더의 realPath string parentPath = realPath.Substring(0, realPath.LastIndexOf('\\')); //부모 폴더의 real path string tarFolderPath = Path.Combine(parentPath, newFolderName); //타겟 폴더의 real path string souFolderFullPath = Path.Combine(serverPath, realPath); //원본 폴더의 전체 path string tarFolderFullPath = Path.Combine(serverPath, tarFolderPath); //타겟 폴더의 전체 path if (renamedfolder != null) { if (!Directory.Exists(tarFolderFullPath)) { Directory.Move(souFolderFullPath, tarFolderFullPath); //RenameFolderRecursive renamedfolder.FolderName = newFolderName; renamedfolder.RealPath = tarFolderPath; renamedfolder.LastModified = DateTime.Now; db.SaveChanges(); } else { return(Ok(new { msg = "같은 이름의 폴더가 존재합니다." })); } } else { return(NotFound()); } } return(Ok(renamedfolder)); }
/// <summary> /// 해당 폴더의 하위 폴더와 파일 path얻기 /// </summary> /// <param name="folderId">해당 폴더 아이디</param> /// <param name="fileList">파일 path가 담겨져 있는 string 리스트</param> /// <returns></returns> public List <string> GetFileList(string folderId, List <string> fileList) { using (var db = new WebDiskDBEntities()) { FolderManage folder = db.FolderManage.Where(x => x.FolderId == folderId && x.OwnerId == HttpContext.Current.User.Identity.Name).SingleOrDefault(); string sourcePath = Path.Combine(folder.ServerPath, folder.OwnerId, folder.RealPath); string folderName = folder.FolderName; #region 하위 파일 path 추가 List <FileManage> subFiles = db.FileManage.Where(x => x.FolderId == folderId && x.OwnerId == HttpContext.Current.User.Identity.Name).ToList(); foreach (var subFile in subFiles) { string subFileName = subFile.FileName + "." + subFile.FileExtension; string subFilePath = Path.Combine(subFile.ServerPath, subFile.OwnerId, subFile.RealPath, subFileName); fileList.Add(subFilePath); } #endregion #region 하위 폴더 path 추가 List <FolderManage> subFolders = db.FolderManage.Where(x => x.ParentId == folderId).ToList(); foreach (var subFolder in subFolders) { GetFileList(subFolder.FolderId, fileList); } #endregion //if (!Directory.Exists(sourcePath)) //{ // response.StatusCode = HttpStatusCode.NotFound; // response.ReasonPhrase = string.Format("Folder not found: {0} .", folderName); // throw new HttpResponseException(response); //} } return(fileList); }
public IHttpActionResult GetDisk(string folderId = null) { string currentUserId = HttpContext.Current.User.Identity.Name; Disk disk = new Disk(); Folder folder = new Folder(); List <FolderManage> subFolderList = null; List <FileManage> subFileList = null; using (var db = new WebDiskDBEntities()) { if (folderId == null) { subFolderList = db.FolderManage.Where(x => x.OwnerId == currentUserId && x.ParentId == null && x.Trashed == false).OrderByDescending(o => o.CreatedDate).ToList(); subFileList = db.FileManage.Where(x => x.OwnerId == currentUserId && x.FolderId == null && x.Trashed == false).OrderByDescending(o => o.CreatedDate).ToList(); } else { FolderManage currentFolder = db.FolderManage.Where(x => x.OwnerId == currentUserId && x.FolderId == folderId && x.Trashed == false).SingleOrDefault(); if (currentFolder != null) { subFolderList = db.FolderManage.Where(x => x.OwnerId == currentUserId && x.ParentId == folderId && x.Trashed == false).OrderByDescending(o => o.CreatedDate).ToList(); subFileList = db.FileManage.Where(x => x.OwnerId == currentUserId && x.FolderId == folderId && x.Trashed == false).OrderByDescending(o => o.CreatedDate).ToList(); } else { return(NotFound()); } } folder.subFolders = subFolderList; folder.subFiles = subFileList; disk.Folder = folder; disk.FolderId = folderId; return(Ok(disk)); } }
/// <summary> /// 폴더 이동 재귀 메소드 호출자는 MoveFolder /// </summary> /// <param name="folderId">해당폴더의 아이디</param> /// <param name="targetPath">타겟폴더의 패스 </param> public void MoveFolderRecursive(string folderId, string targetPath) { using (var db = new WebDiskDBEntities()) { #region 하위 파일 이동하기 List <FileManage> subFiles = db.FileManage.Where(x => x.FolderId == folderId).ToList(); foreach (var file in subFiles) { string fileName = file.FileName + '.' + file.FileExtension; string filePath = Path.Combine(file.ServerPath, file.OwnerId, file.RealPath, fileName); File.Move(filePath, Path.Combine(targetPath, fileName)); string realPath = targetPath.Replace(Path.Combine(file.ServerPath, file.OwnerId), "").TrimStart('\\'); file.RealPath = realPath; db.SaveChanges(); } #endregion #region 하위 폴더 이동하기 List <FolderManage> subFolders = db.FolderManage.Where(x => x.ParentId == folderId).ToList(); foreach (var folder in subFolders) { string sourPath = Path.Combine(folder.ServerPath, folder.OwnerId, folder.RealPath); string tarPath = Path.Combine(targetPath, folder.FolderName); if (!Directory.Exists(tarPath)) { Directory.CreateDirectory(tarPath); } MoveFolderRecursive(folder.FolderId, tarPath); Directory.Delete(sourPath); string realPath = targetPath.Replace(Path.Combine(folder.ServerPath, folder.OwnerId), "").TrimStart('\\'); folder.RealPath = Path.Combine(realPath, folder.FolderName); db.SaveChanges(); } #endregion } }
public IHttpActionResult CreateFolder(FolderManage folder) { FolderManage newFolder = new FolderManage(); string userId = HttpContext.Current.User.Identity.Name; using (var db = new WebDiskDBEntities()) { string folderName = folder.FolderName; string parentId = folder.ParentId; FolderManage parentFolder = db.FolderManage.Where(x => x.FolderId == parentId).SingleOrDefault(); string serverPath = @"C:\WebDisk"; string parentRealPath = parentFolder.RealPath; string folderFullpath = Path.Combine(serverPath, "8d7g9s", parentRealPath); if (!Directory.Exists(folderFullpath)) { Directory.CreateDirectory(folderFullpath); } #region 새로운 폴더 생성 newFolder.FolderId = GenerateUniqueID.FolderID(); //고유 폴더 아이디 생성 newFolder.ParentId = parentId; newFolder.Type = Enum.GetName(typeof(Manage.Enums.ContentType), Manage.Enums.ContentType.Folder).ToLower(); newFolder.ServerPath = serverPath; newFolder.RealPath = Path.Combine(parentRealPath, folderName); newFolder.CreatedDate = DateTime.Now; newFolder.LastAccessed = DateTime.Now; newFolder.LastModified = DateTime.Now; newFolder.FolderName = folderName; newFolder.Starred = false; newFolder.Trashed = false; newFolder.OwnerId = "8d7g9s"; #endregion db.FolderManage.Add(newFolder); db.SaveChanges(); } return(Ok(newFolder)); }
public IHttpActionResult GetRecentFiles(string mimeType) { string userId = HttpContext.Current.User.Identity.Name; byte RR_MimeType = (byte)Manage.Variables.GenerateUniqueID.MyFilesMimeType(mimeType); List <FileManage> mimetypeFiles = null; using (var db = new WebDiskDBEntities()) { mimetypeFiles = db.FileManage.Where(x => x.MimeType == RR_MimeType && x.OwnerId == userId).ToList(); #region 만약 MimeType 을 사용하지않고, 직접 FileExtention 으로 검색 조건을 지정할 시 코드의 예제 if (false) { IQueryable <FileManage> queryList = null; queryList = db.FileManage.Where(x => x.FileExtension == "jpg"); queryList = db.FileManage.Where(x => x.FileExtension == "png"); queryList = db.FileManage.Where(x => x.FileExtension == "gif"); queryList = db.FileManage.Where(x => x.FileExtension == "bmp"); mimetypeFiles = queryList.ToList(); } #endregion } return(Ok(mimetypeFiles)); }
public IHttpActionResult MoveFileToStarred(string fileId, [FromBody] bool starred) { string userId = HttpContext.Current.User.Identity.Name; FileManage currentFile = null; using (var db = new WebDiskDBEntities()) { currentFile = db.FileManage.Where(x => x.FileId == fileId).SingleOrDefault(); if (currentFile != null) { currentFile.Starred = starred; currentFile.LastModified = DateTime.Now; db.SaveChanges(); } else { return(NotFound()); } } return(Ok(currentFile)); }
public IHttpActionResult GetRecentFiles() { string userId = HttpContext.Current.User.Identity.Name; RecentFiles recentFiles = new RecentFiles(); using (var db = new WebDiskDBEntities()) { List <FileManage> allFilesThisYear = db.FileManage.Where(x => (x.LastModified.Value.Year == DateTime.Now.Year || x.LastAccessed.Value.Year == DateTime.Now.Year) && x.Trashed == false && x.OwnerId == userId).ToList(); List <FileManage> todayFiles = new List <FileManage>(); List <FileManage> lastSevenDaysFiles = new List <FileManage>(); List <FileManage> lastThirtyDaysFiles = new List <FileManage>(); List <FileManage> lastSixMonthFiles = new List <FileManage>(); List <FileManage> lastOneYearFiles = new List <FileManage>(); List <FileManage> beforeFiles = new List <FileManage>(); foreach (var file in allFilesThisYear.ToList()) { DateTime Today = DateTime.Now.Date; DateTime lastModifiedDate = file.LastModified.Value.Date; DateTime lastAccessedDate = file.LastAccessed.Value.Date; /* * 오늘(년, 월, 일이 같아야한다) */ if (lastModifiedDate == Today || lastAccessedDate == Today) { todayFiles.Add(file); allFilesThisYear.Remove(file); continue; } /* * 지난7일 * 일주일 전 ~ 어제 */ if ((lastModifiedDate < Today && lastModifiedDate >= DateTime.Now.AddDays(-7).Date) || (lastAccessedDate < Today && lastAccessedDate >= DateTime.Now.AddDays(-7).Date)) { lastSevenDaysFiles.Add(file); allFilesThisYear.Remove(file); continue; } /* * 최근 30일 * 30일 전 ~ 어제 */ if ((lastModifiedDate < Today && lastModifiedDate >= DateTime.Now.AddDays(-30).Date) || (lastAccessedDate < Today && lastAccessedDate >= DateTime.Now.AddDays(-30).Date)) { lastThirtyDaysFiles.Add(file); allFilesThisYear.Remove(file); continue; } //최근 6개월 if ((lastModifiedDate < Today && lastModifiedDate >= DateTime.Now.AddMonths(-6).Date) || (lastAccessedDate < Today && lastAccessedDate >= DateTime.Now.AddMonths(-6).Date)) { lastSixMonthFiles.Add(file); allFilesThisYear.Remove(file); continue; } //최근 1년 if ((lastModifiedDate < Today && lastModifiedDate >= DateTime.Now.AddYears(-1).Date) || (lastAccessedDate < Today && lastAccessedDate >= DateTime.Now.AddYears(-1).Date)) { lastOneYearFiles.Add(file); allFilesThisYear.Remove(file); continue; } // 그 이전 beforeFiles.Add(file); } recentFiles.Today = todayFiles; recentFiles.LastSevenDays = lastSevenDaysFiles; recentFiles.LastThirtyDays = lastThirtyDaysFiles; recentFiles.LastSixMonth = lastSixMonthFiles; recentFiles.LastOneYear = lastOneYearFiles; recentFiles.Before = beforeFiles; } return(Ok(recentFiles)); }
public IHttpActionResult UploadFile() { string userId = HttpContext.Current.User.Identity.Name; //Header에 포함되어 있는 정보 using (var db = new WebDiskDBEntities()) { if (HttpContext.Current.Request.Files.Count > 0) //파일개수가 0이상이면 { HttpFileCollection files = HttpContext.Current.Request.Files; #region 일 등록하기 for (int i = 0; i < files.Count; i++) { var newFile = new FileManage(); HttpPostedFile file = files[i]; if (file.ContentLength > 0)//업로드한 파일의 크기를 가져옴 { string folderId = HttpContext.Current.Request.Form["folderId"]; var parentFolder = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault(); string fileName = Path.GetFileName(file.FileName); string serverPath = @"C:\WebDisk"; string realPath = parentFolder.RealPath; string fullPath = Path.Combine(serverPath, userId, realPath); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } file.SaveAs(Path.Combine(fullPath, fileName)); newFile.FileId = GenerateUniqueID.FileID();//고유 파일 아이디 생성 newFile.FolderId = folderId; newFile.CreatedDate = DateTime.Now; newFile.LastModified = DateTime.Now; newFile.LastAccessed = DateTime.Now; newFile.Type = Enum.GetName(typeof(Manage.Enums.ContentType), Manage.Enums.ContentType.File).ToLower(); newFile.Starred = false; newFile.Trashed = false; newFile.OwnerId = userId; newFile.FileName = Path.GetFileNameWithoutExtension(file.FileName); newFile.FileExtension = Path.GetExtension(file.FileName).TrimStart('.'); //확장자 앞에 있는 '.'제거 newFile.FileSize = (file.ContentLength / 1024); //kb단위로 저장 newFile.RealPath = realPath; newFile.ServerPath = serverPath; #region 업로드된 파일의 마임 타입을 지정한다. Manage.Enums.MimeType isMimeType = Manage.Enums.MimeType.Unknown; switch (newFile.FileExtension.ToLower()) { case "jpg": case "jpeg": case "png": case "gif": case "bmp": isMimeType = Manage.Enums.MimeType.Image; break; case "doc": case "docx": case "xls": case "xlsx": case "pdf": isMimeType = Manage.Enums.MimeType.Document; break; } newFile.MimeType = (byte)isMimeType; #endregion db.FileManage.Add(newFile); db.SaveChanges(); #region 업로드된 파일의 썸네일 생성하기 string rv_FilePreview = Manage.Utils.CreatePreview.CheckFileMap(Path.Combine(fullPath, fileName), newFile.FileId); if (rv_FilePreview.Contains("오류")) { throw new Exception(rv_FilePreview + " << 오류발생했다!!!!"); //1: 원래 생겨야하는 썸네일 등의 이미지를 '파일 썸네일 생성 오류안내' 이미지로 대체한다. //2: 여기에 후속 대체 기능을 추가해야 한다. } else { } #endregion } } #endregion } } return(Ok()); }
/// <summary> /// 하위 폴더와 파일까지 복사하는 재귀 메소드 /// 호출자는 CopyFolder /// </summary> /// <param name="folderId">해당 폴더의 아이디</param> /// <param name="targetFolderId">타겟 폴더 아이디</param> public void CopyFolderRecursive(string folderId, string targetFolderId) { using (var db = new WebDiskDBEntities()) { FolderManage sourceFolder = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault(); FolderManage targetFolder = db.FolderManage.Where(x => x.FolderId == targetFolderId).SingleOrDefault(); if (string.IsNullOrEmpty(targetFolder.OwnerId)) { targetFolder.OwnerId = sourceFolder.OwnerId; } string sourPath = Path.Combine(sourceFolder.ServerPath, sourceFolder.OwnerId, sourceFolder.RealPath); string tarPath = Path.Combine(targetFolder.ServerPath, targetFolder.OwnerId, targetFolder.RealPath, sourceFolder.FolderName); if (!Directory.Exists(tarPath)) { Directory.CreateDirectory(tarPath); } FolderManage copiedFolder = new FolderManage() { FolderId = GenerateUniqueID.FolderID(), FolderName = sourceFolder.FolderName, Type = Enum.GetName(typeof(Manage.Enums.ContentType), Manage.Enums.ContentType.Folder).ToLower(), CreatedDate = DateTime.Now, LastModified = DateTime.Now, LastAccessed = DateTime.Now, OwnerId = sourceFolder.OwnerId, ParentId = targetFolder.FolderId, Starred = false, Trashed = false, ServerPath = sourceFolder.ServerPath, RealPath = Path.Combine(targetFolder.RealPath, sourceFolder.FolderName) }; db.FolderManage.Add(copiedFolder); db.SaveChanges(); #region 하위 파일 복사하기 List <FileManage> subFiles = db.FileManage.Where(x => x.FolderId == folderId).ToList(); foreach (var subFile in subFiles) { string fileName = subFile.FileName + '.' + subFile.FileExtension; string filePath = Path.Combine(subFile.ServerPath, subFile.OwnerId, subFile.RealPath, fileName); string tarFilePath = Path.Combine(tarPath, fileName); if (!File.Exists(tarFilePath)) { File.Copy(filePath, tarFilePath); } FileManage copiedFile = new FileManage() { FileId = GenerateUniqueID.FileID(), FileName = subFile.FileName, Type = Enum.GetName(typeof(Manage.Enums.ContentType), Manage.Enums.ContentType.File).ToLower(), FileExtension = subFile.FileExtension, FileSize = subFile.FileSize, CreatedDate = DateTime.Now, LastModified = DateTime.Now, LastAccessed = DateTime.Now, OwnerId = subFile.OwnerId, Starred = false, Trashed = false, FolderId = copiedFolder.FolderId, RealPath = copiedFolder.RealPath, ServerPath = subFile.ServerPath }; db.FileManage.Add(copiedFile); db.SaveChanges(); } #endregion #region 하위 폴더 복사하기 List <FolderManage> subFolders = db.FolderManage.Where(x => x.ParentId == folderId).ToList(); foreach (var subFolder in subFolders) { CopyFolderRecursive(subFolder.FolderId, copiedFolder.FolderId); } #endregion } }
public HttpResponseMessage DownloadFolder(string folderId) { using (var db = new WebDiskDBEntities()) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); string zipName = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault().FolderName; #region Ionic라이브러리로 파일 압축하기 using (var zip = new Ionic.Zip.ZipFile()) { List <string> fileList = GetFileList(folderId, new List <string>()); foreach (var file in fileList) { try { #region 일을 읽어와서 zip entry에 추가 //todo : file 이란 변수가 실제로 파일인것만 stream으로 생성하여 압축 entry 에 추가하기.. //Bytes 배열로 생성 byte[] bytes_file = File.ReadAllBytes(file); #region 해당 폴더 경로만 얻기 int index = file.IndexOf(zipName); //해당 폴더 인덱스 string parsedPath = file.Substring(0, index); //인덱스까지 문자열을 자른다. string result = file.Replace(parsedPath, ""); //파싱한 문자열을 제거한다 //시스템의 기본 인코딩 타입으로 읽어서 byte[] __filename_bytec = System.Text.Encoding.Default.GetBytes(result); // IBM437로 변환해 준다. string IS_FileName = System.Text.Encoding.GetEncoding("IBM437").GetString(__filename_bytec); zip.AddEntry(IS_FileName, bytes_file); #endregion #endregion } catch { return(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("오류발생 : " + file, System.Text.Encoding.UTF8) }); } } #region 메모리스트림에 zip 파일 저장하기 zip파일로 리턴하기 using (MemoryStream memoryStream = new MemoryStream()) { zip.Save(memoryStream); response.Content = new ByteArrayContent(memoryStream.ToArray()); response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = $"{zipName}_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.zip"; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); } #endregion } #endregion return(response); } }