public Task <bool> DeleteFilesAsync(FilesDTO objFilesDTO) { int intFilesId = Convert.ToInt32(objFilesDTO.FileId); var ExistingFiles = _context.Files .Where(x => x.FileId == intFilesId) .FirstOrDefault(); if (ExistingFiles != null) { _context.Files.Remove(ExistingFiles); _context.SaveChanges(); // Delete the file FileController objFileController = new FileController(_environment); objFileController.DeleteFile(objFilesDTO.FilePath); } else { return(Task.FromResult(false)); } return(Task.FromResult(true)); }
public HttpResponseMessage DownloadFile([FromUri] FilesDTO fileDTO) { HttpResponseMessage result = null; FilesDTO filesDTO = FilesBAL.GetFileByFileIdAndUserId(fileDTO.Id, fileDTO.CreatedBy); if (filesDTO == null) { result = Request.CreateResponse(HttpStatusCode.BadRequest); } else { var localFilePath = HttpContext.Current.Server.MapPath("~/Uploads/" + filesDTO.Name); if (!File.Exists(localFilePath)) { result = Request.CreateResponse(HttpStatusCode.Gone); } else { result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read)); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = filesDTO.Name; } } return(result); }
public HttpResponseMessage GetThumbnail([FromUri] FilesDTO fileDTO) { HttpResponseMessage response = null; fileDTO = FilesBAL.GetFileByFileIdAndUserId(fileDTO.Id, fileDTO.CreatedBy); if (fileDTO == null) { response = Request.CreateResponse(HttpStatusCode.NotFound); } else { string path = HttpContext.Current.Server.MapPath("~/Uploads/" + fileDTO.Name); if (!File.Exists(path)) { response = Request.CreateResponse(HttpStatusCode.NotFound); } ShellFile shellFile = ShellFile.FromFilePath(path); Bitmap shellThumb = shellFile.Thumbnail.MediumBitmap; byte[] file = ImageToBytes(shellThumb); MemoryStream ms = new MemoryStream(file); response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new ByteArrayContent(file); response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileDTO.Name; } return(response); }
public async Task <IActionResult> Post([FromBody] FilesDTO file) { if (_uow.FileRepository.CheckFile55(file.FileNum55.Trim().ToLower())) { ModelState.AddModelError("", "عفوا رقم ملف 55 مسجل من قبل "); } if (!ModelState.IsValid) { return(BadRequest(ModelState.Keys.SelectMany(key => ModelState[key].Errors))); } file.Name = file.Name.Trim().ToLower(); file.FileNum55 = file.FileNum55.Trim().ToLower(); file.EntryName = User.Identity.Name; file.CreatedDate = DateTime.Now; try { var fileToReturn = _mapper.Map <Models.File> (file); _uow.FileRepository.Add(fileToReturn); await _uow.SaveChangesAsync(); return(Ok(fileToReturn)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <IActionResult> SingleAsync( IFormFile file, string FileTitle) { try { if (HttpContext.Request.Form.Files.Any()) { // Only accept .zip files if (file.ContentType == "application/x-zip-compressed") { string path = Path.Combine( environment.WebRootPath, "files", file.FileName); // Create directory if not exists string directoryName = Path.GetDirectoryName(path); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } // Save to database if (FileTitle == "") { FileTitle = "[Unknown]"; } FilesDTO objFilesDTO = new FilesDTO(); objFilesDTO.FileName = FileTitle; objFilesDTO.FilePath = file.FileName; BlogsService objBlogsService = new BlogsService(blogsContext, environment); await objBlogsService.CreateFilesAsync(objFilesDTO); } } return(StatusCode(200)); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
public int UploadFileByParentFolderIdAndUserId() { int id = 0; if (HttpContext.Current.Request.Files.Count > 0) { try { string name = ""; string fileExt = ""; int fileSizeInKB = 0; foreach (var fileName in HttpContext.Current.Request.Files.AllKeys) { HttpPostedFile file = HttpContext.Current.Request.Files[fileName]; if (file != null) { fileSizeInKB = file.ContentLength / 1024; if ((fileSizeInKB / 1024) > 8) { return(0); } fileExt = Path.GetExtension(file.FileName); name = file.FileName; string rootPath = HttpContext.Current.Server.MapPath("~/Uploads"); string fileSavePath = Path.Combine(rootPath, name); file.SaveAs(fileSavePath); } } //end of foreach FilesDTO filesDTO = new FilesDTO(); filesDTO.Name = name; filesDTO.ParentFolderId = Convert.ToInt32(HttpContext.Current.Request["ParentFolderId"]); filesDTO.FileExt = fileExt; filesDTO.FileSizeInKB = fileSizeInKB; filesDTO.CreatedBy = Convert.ToInt32(HttpContext.Current.Request["CreatedBy"]); filesDTO.UploadedOn = DateTime.Now; filesDTO.IsActive = true; id = FilesBAL.CreateFile(filesDTO); } catch (Exception ex) { return(id); } } //end of if count > 0 return(id); }
public async Task <IActionResult> PutFile([FromBody] FilesDTO file) { //TODO يمكن تكرارا رقم 55 // if (_uow.FileRepository.CheckFile55 (file.FileNum55.Trim ().ToLower ())) { // ModelState.AddModelError ("", "عفوا رقم ملف 55 مسجل من قبل "); // } if (!ModelState.IsValid) { return(BadRequest(ModelState.Keys.SelectMany(key => ModelState[key].Errors))); } var fileToDB = _mapper.Map <Models.File> (file); _uow.FileRepository.Update(fileToDB); await _uow.SaveChangesAsync(); return(Ok()); }
/// <summary> /// 上传文件 /// </summary> /// <param name="file"></param> /// <returns></returns> public JsonResult ImportData(HttpPostedFileBase file) { var checkResult = new CheckDataResult { Result = false }; if (file == null) { checkResult.ErrorMessages.Add("找不到上传的文件!"); return(Json(checkResult, JsonRequestBehavior.AllowGet)); } var fileName = file.FileName; var ext = fileName.Substring(fileName.LastIndexOf(".")); if (!ext.InStr(".txt", ".doc", ".docx", ".xls", ".xlsx", ".jpg", ".png", ".xmind", ".rar", ".zip")) { checkResult.ErrorMessages.Add("文件格式不正确,仅支持:txt、doc、xls、jpg、png、xmind、rar、zip文件!"); return(Json(checkResult, JsonRequestBehavior.AllowGet)); } var entity = new FilesDTO(); entity.file_name = fileName.Replace(ext, ""); entity.file_ext = ext; entity.file_key = Guid.NewGuid().ToString("N").ToUpper() + ext; entity.file_timestamp = DateTime.Now; byte[] fileBytes = null; fileBytes = new byte[file.ContentLength]; file.InputStream.Read(fileBytes, 0, file.ContentLength); entity.file_bytes = fileBytes; CacheHelper.SetCacheValue(entity.file_key, entity, 24 * 60); checkResult.Result = true; checkResult.Entity = new FilesDTO() { file_key = entity.file_key, file_name = entity.file_name }; return(Json(checkResult, JsonRequestBehavior.AllowGet)); }
public Task <bool> CreateFilesAsync(FilesDTO objFilesDTO) { try { Files objFiles = new Files(); objFiles.CreateDate = DateTime.Now; objFiles.DownloadCount = 0; objFiles.FileName = objFilesDTO.FileName; objFiles.FilePath = objFilesDTO.FilePath; _context.Files.Add(objFiles); _context.SaveChanges(); return(Task.FromResult(true)); } catch (Exception ex) { DetachAllEntities(); throw ex; } }
public Task <bool> UpdateFilesAsync(FilesDTO objFilesDTO) { try { int intFilesId = Convert.ToInt32(objFilesDTO.FileId); var ExistingFiles = _context.Files .Where(x => x.FileId == intFilesId) .FirstOrDefault(); if (ExistingFiles != null) { ExistingFiles.DownloadCount = objFilesDTO.DownloadCount; ExistingFiles.FileName = objFilesDTO.FileName; ExistingFiles.FilePath = objFilesDTO.FilePath; _context.SaveChanges(); } else { return(Task.FromResult(false)); } return(Task.FromResult(true)); } catch (Exception ex) { DetachAllEntities(); throw ex; } }
public static int CreateFile(FilesDTO filesDTO) { string connectionString = null; SqlConnection connection = null; SqlCommand sqlCommand = null; SqlParameter sqlParameter = null; int id = 0; try { connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; connection = new SqlConnection(connectionString); connection.Open(); string sql = @"INSERT INTO dbo.Files ( Name, ParentFolderId, FileExt, FileSizeInKB, CreatedBy, UploadedOn, IsActive ) VALUES ( @Name, @ParentFolderId, @FileExt, @FileSizeInKB, @CreatedBy, @UploadedOn, @IsActive ); SELECT SCOPE_IDENTITY()" ; sqlCommand = new SqlCommand(sql, connection); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "Name"; sqlParameter.SqlDbType = System.Data.SqlDbType.VarChar; sqlParameter.Value = filesDTO.Name; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "ParentFolderId"; sqlParameter.SqlDbType = System.Data.SqlDbType.Int; sqlParameter.Value = filesDTO.ParentFolderId; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "FileExt"; sqlParameter.SqlDbType = System.Data.SqlDbType.VarChar; sqlParameter.Value = filesDTO.FileExt; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "FileSizeInKB"; sqlParameter.SqlDbType = System.Data.SqlDbType.Int; sqlParameter.Value = filesDTO.FileSizeInKB; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "CreatedBy"; sqlParameter.SqlDbType = System.Data.SqlDbType.Int; sqlParameter.Value = filesDTO.CreatedBy; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "UploadedOn"; sqlParameter.SqlDbType = System.Data.SqlDbType.DateTime; sqlParameter.Value = filesDTO.UploadedOn; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "IsActive"; sqlParameter.SqlDbType = System.Data.SqlDbType.Bit; sqlParameter.Value = filesDTO.IsActive; sqlCommand.Parameters.Add(sqlParameter); id = Convert.ToInt32(sqlCommand.ExecuteScalar()); } catch (Exception ex) { return(0); } finally { if (sqlCommand != null) { sqlCommand.Dispose(); } if (connection != null) { connection.Close(); } } return(id); }
public static FilesDTO GetFileByFileIdAndUserId(int FileId, int UserId) { string connectionString = null; SqlConnection connection = null; SqlCommand sqlCommand = null; SqlParameter sqlParameter = null; SqlDataReader sqlDataReader = null; FilesDTO filesDTO = null; try { connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; connection = new SqlConnection(connectionString); connection.Open(); string sql = @"SELECT * FROM dbo.Files WHERE IsActive = 'true' AND Id = @FileId AND CreatedBy = @UserId" ; sqlCommand = new SqlCommand(sql, connection); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "FileId"; sqlParameter.SqlDbType = System.Data.SqlDbType.Int; sqlParameter.Value = FileId; sqlCommand.Parameters.Add(sqlParameter); sqlParameter = new SqlParameter(); sqlParameter.ParameterName = "UserId"; sqlParameter.SqlDbType = System.Data.SqlDbType.Int; sqlParameter.Value = UserId; sqlCommand.Parameters.Add(sqlParameter); sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read()) { filesDTO = new FilesDTO(); filesDTO.Id = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("Id")); filesDTO.Name = sqlDataReader.GetString(sqlDataReader.GetOrdinal("Name")); filesDTO.ParentFolderId = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("ParentFolderId")); filesDTO.FileExt = sqlDataReader.GetString(sqlDataReader.GetOrdinal("FileExt")); filesDTO.FileSizeInKB = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("FileSizeInKB")); filesDTO.CreatedBy = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("CreatedBy")); filesDTO.UploadedOn = sqlDataReader.GetDateTime(sqlDataReader.GetOrdinal("UploadedOn")); filesDTO.IsActive = sqlDataReader.GetBoolean(sqlDataReader.GetOrdinal("IsActive")); } } catch (Exception ex) { return(null); } finally { if (sqlDataReader != null) { sqlDataReader.Close(); } if (sqlCommand != null) { sqlCommand.Dispose(); } if (connection != null) { connection.Close(); } } return(filesDTO); }
public static int CreateFile(FilesDTO filesDTO) { return(FilesDAL.CreateFile(filesDTO)); }
public bool DeleteFileByFileIdAndUserId(FilesDTO fileDTO) { return(FilesBAL.DeleteFileByFileIdAndUserId(fileDTO.Id, fileDTO.CreatedBy)); }
public List <FilesDTO> GetFilesByParentFolderIdAndUserId(FilesDTO fileDTO) { return(FilesBAL.GetFilesByParentFolderIdAndUserId(fileDTO.ParentFolderId, fileDTO.CreatedBy)); }