public ResponseModel ProcessFile(string file) { if (String.IsNullOrEmpty(file) || !File.Exists(file)) { var message = "해당 파일이 존재하지 않습니다."; return(ResponseModel.ErrorMessage(new FileNotFoundException(fileName: file, message: message), message)); } FileInfo fileInfo = new FileInfo(file); byte[] buffer = null; using (var stream = fileInfo.OpenRead()) { using (var reader = new BinaryReader(stream)) { buffer = reader.ReadBytes((int)fileInfo.Length); reader.Close(); } stream.Close(); } return(new FileResponseModel { // TODO Uri encode가 필요한가? FileName = fileInfo.Name, // https://developer.mozilla.org/ko/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types ContentType = "application/octet-stream", Content = buffer, }); }
public ResponseModel ProcessException(Exception ex) { if (ex is ServiceException) { return(ResponseModel.ErrorMessage(ex)); } // TODO 예외 메시지를 바로 출력할 것인가? return(ResponseModel.ErrorMessage(ex)); }
private static void UploadHandler(IApplicationBuilder app) { app.Run(async(context) => { var loggerFactory = app.ApplicationServices.GetService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger("UploadHandler"); var httpContextManager = app.ApplicationServices.GetService <IHttpContextManager>(); var fileManager = app.ApplicationServices.GetService <IFileManager>(); RequestModel requestModel = null; ResponseModel responseModel = null; try { requestModel = await httpContextManager.ParseRequestData(); responseModel = await fileManager.UploadFile(requestModel); } catch (ServiceException ex) { responseModel = ResponseModel.ErrorMessage(ex); } catch (Exception ex) { logger.LogError(ex, $"{nameof(UploadHandler)}: {ex.Message}"); responseModel = ResponseModel.Message("100", "파일업로드 에러가 발생했습니다."); } if (responseModel == null) { responseModel = ResponseModel.DefaultMessage; } await context.ExecuteResponseModelResult(responseModel); }); }
public async Task <ResponseModel> UploadFile(RequestModel model) { ResponseModel responseModel = null; try { /*웹서버 세션 정보 체크*/ string sessionID = httpContextManager.GetSessionId(); string client_SessionID = model.GetValue(Constants.SESSIONID_KEY_STRING); if (Constants.SESSION_CHECK && String.IsNullOrWhiteSpace(client_SessionID)) { throw new ServiceException("세션정보가 빈값이거나, 세션 정보를 넘기지 않습니다. 로그인 후 사용바랍니다."); } else if (Constants.SESSION_CHECK && httpContextManager.CheckSessionId(client_SessionID)) { throw new ServiceException("세션 정보가 올바르지 않습니다. 다시 로그인한 후 사용바랍니다."); } var formFiles = httpContextManager.GetFormFiles(); /*파일 업로드 갯수 제한*/ if (formFiles.Count == 0) { throw new ServiceException("업로드 파일이 없습니다."); } else if (formFiles.Count > 1) { throw new ServiceException("파일은 하나씩만 업로드 가능합니다."); } //저장위치를 지정 //string uploadDir = ConfigurationManager.AppSettings["etc"]; var uploadDir = appOptions.Etc; uploadDir = GetATTACHMENT_UPLOAD_PATH(model); //디렉토리 체크 if (!Directory.Exists(uploadDir)) { try { Directory.CreateDirectory(uploadDir); } catch (Exception ex) { throw new ServiceException("파일경로를 만들 수 없습니다.", ex); } } // 파일을 저장하고,(+이미지 파일일 경우 섬네일이미지를 생성하고 - 구현안됨) foreach (var file in formFiles) { //HttpPostedFile file = _context.Request.Files[fileKey]; //파일이름을 지정하여 저장할 것인가? file_name string namedFileName = model.GetValue(Constants.ATTACHMENT_FILENAME_key); string fileFullPath = String.Empty; if (!String.IsNullOrEmpty(namedFileName)) { fileFullPath = Path.Join(uploadDir, namedFileName); } else { fileFullPath = Path.Join(uploadDir, file.FileName); } fileFullPath = MakeUniqueFileName(fileFullPath); using (var stream = file.OpenReadStream()) { using (var destinationStream = new FileStream(fileFullPath, FileMode.Create, FileAccess.Write)) { await stream.CopyToAsync(destinationStream); await destinationStream.FlushAsync(); destinationStream.Close(); } stream.Close(); } FileInfo fileInfo = new FileInfo(fileFullPath); var attachment_filename = fileInfo.Name; var attachment_fileformat = fileInfo.Extension; var attachment_filesize = fileInfo.Length; // 디비를 저장하고 // 디비에 저장할 것인가? db_work string isDBWork = model.GetValue(Constants.DB_WORK_GUBUN_value); string return_msg = string.Empty; string resultXML = String.Empty; if (!String.IsNullOrEmpty(isDBWork) && !isDBWork.Equals("pass")) { //db_work=pass 명시적으로 표시할 경우 디비 작업 없음. // TODO 메시지가 없어서 추가 responseModel = ResponseModel.Message("1", "요청하신 파일이 업로드되었습니다."); } else { var dataSet = await Attachment_CRDAsync(CRUD.C, model, new FileModel { Name = attachment_filename, Format = attachment_fileformat, Size = attachment_filesize, }); responseModel = responsePreprocessManager.ProcessDataSet(dataSet); } } } catch (ServiceException ex) { responseModel = ResponseModel.ErrorMessage(ex); } catch (Exception ex) { responseModel = ResponseModel.Message("100", "파일업로드 에러가 발생했습니다."); //responseModel = ResponseModel.ErrorMessage(ex); } return(responseModel); }
public async Task <ResponseModel> DeleteFile(RequestModel model) { /* * gubun = file_delete * (옵션1)************************************ * attachment_key = string * (옵션2)************************************ * attachment_gubun = string * file_name = string * db_work = pass */ string fileFullPath = string.Empty; ResponseModel responseModel = null; if (model.HasKey(Constants.ATTACHMENT_KEY_key)) { fileFullPath = await this.ReturnFileFullPath(model); } else { string namedFileName = model.GetValue(Constants.ATTACHMENT_FILENAME_key); if (!string.IsNullOrEmpty(namedFileName)) { var uploadPath = GetATTACHMENT_UPLOAD_PATH(model); fileFullPath = System.IO.Path.Join(uploadPath, namedFileName); } else { fileFullPath = string.Empty; } } try { if (String.IsNullOrEmpty(fileFullPath)) { throw new ServiceException("삭제할 파일 정보가 올바르지 않습니다.(파일 삭제 방식을 체크하세요.)"); } //가져온 파일정보의 실제 파일을 삭제한다. if (File.Exists(fileFullPath)) { FileInfo fi = new FileInfo(fileFullPath); string fileName = fi.Name; string dirName = fi.DirectoryName; if (!fileName.StartsWith("_del_")) { //string fileFullPath2 = string.Format(@"{0}\{1}", dirName, "_del_" + fileName); string fileFullPath2 = Path.Join(dirName, "_del_", fileName); fileFullPath2 = this.MakeUniqueFileName(fileFullPath2); fi.MoveTo(fileFullPath2); } //File.Delete(fileFullPath);//실제 삭제하지 않음. } //디비에서 해당 파일항목을 삭제한다. string isDBWork = model.GetValue(Constants.DB_WORK_GUBUN_value); if (!string.IsNullOrEmpty(isDBWork) && !isDBWork.Equals("pass")) { //db_work=pass 명시적으로 표시할 경우 디비 작업 없음. } else { await Attachment_CRDAsync(CRUD.D, model, FileModel.Empty); } //responseModel = ResponseModel.Message("1", "파일 삭제완료.\r\n" + msg); responseModel = ResponseModel.Message("1", "파일 삭제완료."); } catch (ServiceException ex) { responseModel = responsePreprocessManager.ProcessException(ex); } catch (Exception ex) { //throw new ServiceException("httpservice(DeleteFile).Error check", ex); responseModel = ResponseModel.ErrorMessage(ex, "httpservice(DeleteFile).Error check"); } return(responseModel); }