단속자료 파일업로드 기능 추가

dev
박성영 1 month ago
parent b11649a4ec
commit 5cfe3a7080

@ -0,0 +1,7 @@
CREATE SEQUENCE seq_crdn_file_id
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 9999999999999999
CACHE 1000
NOCYCLE;

@ -0,0 +1,16 @@
create table tb_crdn_file
(
FILE_ID varchar(20) not null comment '파일 ID'
primary key,
CRDN_YR char(4) null comment '단속 연도',
CRDN_NO varchar(6) null comment '단속 번호',
ORIGINAL_FILE_NM varchar(200) not null comment '원본 파일명',
STORED_FILE_NM varchar(200) not null comment '저장 파일명',
FILE_PATH varchar(200) not null comment '파일 경로',
FILE_SIZE bigint not null comment '파일 크기',
FILE_EXT varchar(10) not null comment '파일 확장자',
REG_DTTM datetime null comment '등록 일시',
RGTR varchar(20) null comment '등록자'
)
comment '단속관련 파일 파일';

@ -1,14 +1,19 @@
package go.kr.project.crdn.crndRegistAndView.main.controller;
import egovframework.constant.FileContentTypeConstants;
import egovframework.constant.MessageConstants;
import egovframework.constant.TilesConstants;
import egovframework.exception.MessageException;
import egovframework.util.ApiResponseUtil;
import egovframework.util.FileUtil;
import egovframework.util.SessionUtil;
import egovframework.util.excel.ExcelSheetData;
import egovframework.util.excel.SxssfExcelFile;
import go.kr.project.common.model.CmmnCodeSearchVO;
import go.kr.project.common.model.FileVO;
import go.kr.project.common.service.CommonCodeService;
import go.kr.project.crdn.crndRegistAndView.main.mapper.CrdnFileMapper;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnFileVO;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnRegistAndViewExcelGridVO;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnRegistAndViewExcelVO;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnRegistAndViewVO;
@ -21,14 +26,18 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
@ -50,6 +59,9 @@ import java.util.List;
@Tag(name = "단속 등록/조회", description = "단속 등록/조회 관련 API")
public class CrdnRegistAndViewController {
@Value("${file.upload.max-files:10}")
private int maxFiles;
/** 단속 서비스 */
private final CrdnRegistAndViewService service;
@ -58,6 +70,10 @@ public class CrdnRegistAndViewController {
private final CommonCodeService commonCodeService;
private final CrdnFileMapper crdnFileMapper;
private final FileUtil fileUtil;
/**
* , .
* @param model
@ -208,7 +224,16 @@ public class CrdnRegistAndViewController {
.sortAscending(true)
.build();
model.addAttribute("dsclMthdCdList", commonCodeService.selectCodeDetailList(dsclMthdCdSearchVO));
CrdnFileVO paramVO = CrdnFileVO.builder()
.crdnYr(crdnYr)
.crdnNo(crdnNo)
.build();
model.addAttribute("crdnFileList", crdnFileMapper.selectCrdnFileList(paramVO));
// 최대 파일 개수 전달
model.addAttribute("maxFiles", 5);
return "crdn/crndRegistAndView/main/detailView-main" + TilesConstants.BASE;
}
@ -242,8 +267,9 @@ public class CrdnRegistAndViewController {
/**
* .
*
*
* @param paramVO VO
* @param request MultipartHttpServletRequest
* @return ResponseEntity
*/
@Operation(summary = "단속 수정", description = "기존 단속 정보를 수정합니다.")
@ -253,11 +279,14 @@ public class CrdnRegistAndViewController {
@ApiResponse(description = "오류로 인한 실패")
})
@PostMapping("/update.ajax")
public ResponseEntity<?> update(@ModelAttribute CrdnRegistAndViewVO paramVO) {
public ResponseEntity<?> update(@ModelAttribute CrdnRegistAndViewVO paramVO, MultipartHttpServletRequest request) {
log.debug("단속 정보 수정 요청 - 단속연도: {}, 단속번호: {}", paramVO.getCrdnYr(), paramVO.getCrdnNo());
int result = service.update(paramVO);
// 파일 목록 가져오기
List<MultipartFile> fileList = request.getFiles("files");
int result = service.updateWithFiles(paramVO, fileList);
if (result > 0) {
return ApiResponseUtil.success(MessageConstants.Common.UPDATE_SUCCESS);
} else {
@ -467,5 +496,70 @@ public class CrdnRegistAndViewController {
}
}
/**
* .
*
* @param crdnYr
* @param crdnNo
* @return ResponseEntity
*/
@Operation(summary = "첨부파일 목록 조회", description = "단속의 첨부파일 목록을 조회합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "첨부파일 목록 조회 성공"),
@ApiResponse(responseCode = "400", description = "첨부파일 목록 조회 실패"),
@ApiResponse(description = "오류로 인한 실패")
})
@GetMapping("/fileList.ajax")
public ResponseEntity<?> fileListAjax(@RequestParam String crdnYr, @RequestParam String crdnNo) {
CrdnFileVO paramVO = CrdnFileVO.builder()
.crdnYr(crdnYr)
.crdnNo(crdnNo)
.build();
List<CrdnFileVO> fileList = crdnFileMapper.selectCrdnFileList(paramVO);
return ApiResponseUtil.success(fileList, "첨부파일 목록 조회가 완료되었습니다.");
}
/**
* .
*
* @param fileId ID
* @return ResponseEntity
*/
@Operation(summary = "첨부 파일 삭제", description = "단속의 첨부 파일을 삭제합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "첨부 파일 삭제 성공"),
@ApiResponse(responseCode = "400", description = "첨부 파일 삭제 실패"),
@ApiResponse(description = "오류로 인한 실패")
})
@PostMapping("/deleteFile.ajax")
public ResponseEntity<?> deleteFileAjax(@RequestParam String fileId) {
int result = service.deleteCrdnFile(fileId);
if (result > 0) {
return ApiResponseUtil.success("파일이 성공적으로 삭제되었습니다.");
} else {
return ApiResponseUtil.error("파일 삭제에 실패했습니다.");
}
}
/**
* .
*
* @param fileId ID
* @param request HTTP
* @param response HTTP
*/
@Operation(summary = "첨부 파일 다운로드", description = "단속의 첨부 파일을 다운로드합니다.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "첨부 파일 다운로드 성공"),
@ApiResponse(responseCode = "400", description = "첨부 파일 다운로드 실패"),
@ApiResponse(description = "오류로 인한 실패")
})
@GetMapping("/download.do")
public void downloadFile(@RequestParam String fileId, HttpServletRequest request, HttpServletResponse response) {
// 파일 다운로드 처리 - 서비스 계층으로 위임
service.downloadCrdnFile(fileId, request, response);
}
}

@ -0,0 +1,68 @@
package go.kr.project.crdn.crndRegistAndView.main.mapper;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnFileVO;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* packageName : go.kr.project.crdn.crndRegistAndView.main.mapper
* fileName : CrdnFileMapper
* author :
* date : 2025-11-14
* description : Mapper
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2025-11-14
*/
@Mapper
public interface CrdnFileMapper {
/**
* .
*
* @param fileId ID
* @return
*/
CrdnFileVO selectCrdnFile(String fileId);
/**
* .
*
* @param vo (crdnYr, crdnNo)
* @return
*/
List<CrdnFileVO> selectCrdnFileList(CrdnFileVO vo);
/**
* ID .
*
* @return CRDF00000001 ID
*/
String generateFileId();
/**
* .
*
* @param vo VO
* @return
*/
int insertCrdnFile(CrdnFileVO vo);
/**
* .
*
* @param vo (crdnYr, crdnNo)
* @return
*/
int deleteCrdnFileByCrdn(CrdnFileVO vo);
/**
* .
*
* @param fileId ID
* @return
*/
int deleteCrdnFile(String fileId);
}

@ -0,0 +1,83 @@
package go.kr.project.crdn.crndRegistAndView.main.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
/**
* packageName : go.kr.project.crdn.crndRegistAndView.main.model
* fileName : CrdnFileVO
* author :
* date : 2025-11-14
* description : VO
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2025-11-14
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class CrdnFileVO {
/** 파일 ID */
@Size(max = 20)
private String fileId;
/** 단속 연도 */
@Size(max = 4)
@NotNull
private String crdnYr;
/** 단속 번호 */
@Size(max = 10)
@NotNull
private String crdnNo;
/** 원본 파일명 */
@Size(max = 200)
@NotNull
private String originalFileNm;
/** 저장 파일명 */
@Size(max = 200)
@NotNull
private String storedFileNm;
/** 파일 경로 */
@Size(max = 200)
@NotNull
private String filePath;
/** 파일 크기 */
@NotNull
private Long fileSize;
/** 파일 확장자 */
@Size(max = 10)
@NotNull
private String fileExt;
/** 등록 일시 */
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Seoul")
private LocalDateTime regDttm;
/** 등록자 */
@Size(max = 10)
private String rgtr;
// ==================== 추가 필드 (표시용) ====================
/** 파일 크기 표시용 (KB, MB 등) */
private String fileSizeStr;
/** 다운로드 URL */
private String downloadUrl;
}

@ -108,4 +108,30 @@ public interface CrdnRegistAndViewService {
*/
List<CrdnRegistAndViewExcelVO> selectListForExcel(CrdnRegistAndViewVO vo);
/**
* .
*
* @param vo VO
* @param files
* @return
*/
int updateWithFiles(CrdnRegistAndViewVO vo, java.util.List<org.springframework.web.multipart.MultipartFile> files);
/**
* .
*
* @param fileId ID
* @return
*/
int deleteCrdnFile(String fileId);
/**
* .
*
* @param fileId ID
* @param request HTTP
* @param response HTTP
*/
void downloadCrdnFile(String fileId, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response);
}

@ -1,10 +1,15 @@
package go.kr.project.crdn.crndRegistAndView.main.service.impl;
import egovframework.constant.CrdnPrcsSttsConstants;
import egovframework.constant.FileContentTypeConstants;
import egovframework.exception.MessageException;
import egovframework.util.FileUtil;
import egovframework.util.SessionUtil;
import egovframework.util.StringUtil;
import go.kr.project.common.model.FileVO;
import go.kr.project.crdn.crndRegistAndView.main.mapper.CrdnFileMapper;
import go.kr.project.crdn.crndRegistAndView.main.mapper.CrdnRegistAndViewMapper;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnFileVO;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnRegistAndViewExcelGridVO;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnRegistAndViewExcelVO;
import go.kr.project.crdn.crndRegistAndView.main.model.CrdnRegistAndViewVO;
@ -13,8 +18,14 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static egovframework.constant.SEQConstants.SEQ_CRDN;
@ -38,6 +49,8 @@ import static egovframework.constant.SEQConstants.SEQ_CRDN;
public class CrdnRegistAndViewServiceImpl extends EgovAbstractServiceImpl implements CrdnRegistAndViewService {
private final CrdnRegistAndViewMapper mapper;
private final CrdnFileMapper crdnFileMapper;
private final FileUtil fileUtil;
/**
* .
@ -218,18 +231,18 @@ public class CrdnRegistAndViewServiceImpl extends EgovAbstractServiceImpl implem
* @throws MessageException
*/
private void validateRequiredFields(CrdnRegistAndViewVO vo) {
if (vo.getRgnSeCd() == null || vo.getRgnSeCd().trim().isEmpty()) {
/*if (vo.getRgnSeCd() == null || vo.getRgnSeCd().trim().isEmpty()) {
log.warn("단속 작업 실패 - 지역구분코드 미입력");
throw new MessageException("지역구분은 필수값입니다.");
}
}*/
if (vo.getDsclMthdCd() == null || vo.getDsclMthdCd().trim().isEmpty()) {
log.warn("단속 작업 실패 - 적발방법코드 미입력");
throw new MessageException("적발방법은 필수값입니다.");
}
if (vo.getRelevyYn() == null || vo.getRelevyYn().trim().isEmpty()) {
/*if (vo.getRelevyYn() == null || vo.getRelevyYn().trim().isEmpty()) {
log.warn("단속 작업 실패 - 재부과여부 미입력");
throw new MessageException("재부과여부는 필수값입니다.");
}
}*/
}
/**
@ -316,4 +329,158 @@ public class CrdnRegistAndViewServiceImpl extends EgovAbstractServiceImpl implem
log.debug("엑셀 다운로드용 단속 목록 조회 완료 - 조회 건수: {}", list.size());
return list;
}
/**
* .
*
* @param vo VO
* @param files
* @return
*/
@Override
@Transactional
public int updateWithFiles(CrdnRegistAndViewVO vo, List<MultipartFile> files) {
log.debug("단속 정보 파일 포함 수정 - 단속연도: {}, 단속번호: {}", vo.getCrdnYr(), vo.getCrdnNo());
// 단속 정보 수정
int result = update(vo);
// 파일 업로드 처리
if (files != null && !files.isEmpty()) {
uploadCrdnFiles(files, vo.getCrdnYr(), vo.getCrdnNo(), SessionUtil.getUserId());
}
return result;
}
/**
* DB . ( )
*
* @param files
* @param crdnYr
* @param crdnNo
* @param rgtr
* @return
*/
private List<CrdnFileVO> uploadCrdnFiles(List<MultipartFile> files, String crdnYr, String crdnNo, String rgtr) {
List<CrdnFileVO> result = new ArrayList<>();
if (files == null || files.isEmpty()) {
return result;
}
// 빈 파일 제거
List<MultipartFile> validFiles = new ArrayList<>();
for (MultipartFile file : files) {
if (!file.isEmpty()) {
validFiles.add(file);
}
}
if (validFiles.isEmpty()) {
return result;
}
// FileUtil을 사용하여 파일 업로드
List<FileVO> uploadedFiles;
try {
// 설정 파일에서 하위 디렉토리 경로 가져오기
String subDir = fileUtil.getSubDir("crdn-file");
uploadedFiles = fileUtil.uploadFiles(validFiles, subDir);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (FileVO uploadedFile : uploadedFiles) {
// 파일 ID 생성
String fileId = crdnFileMapper.generateFileId();
// 파일 정보 VO 생성
CrdnFileVO fileVO = CrdnFileVO.builder()
.fileId(fileId)
.crdnYr(crdnYr)
.crdnNo(crdnNo)
.originalFileNm(uploadedFile.getOriginalFileNm())
.storedFileNm(uploadedFile.getStoredFileNm())
.filePath(uploadedFile.getFilePath())
.fileSize(uploadedFile.getFileSize())
.fileExt(uploadedFile.getFileExt())
.rgtr(rgtr)
.build();
// 파일 정보 DB 등록
crdnFileMapper.insertCrdnFile(fileVO);
result.add(fileVO);
}
return result;
}
/**
* .
*
* @param fileId ID
* @return
*/
@Override
@Transactional
public int deleteCrdnFile(String fileId) {
// 파일 정보 조회
CrdnFileVO fileVO = crdnFileMapper.selectCrdnFile(fileId);
int result = crdnFileMapper.deleteCrdnFile(fileId);
if (result > 0 && fileVO != null) {
// FileVO로 변환
FileVO fileInfo = new FileVO();
fileInfo.setOriginalFileNm(fileVO.getOriginalFileNm());
fileInfo.setStoredFileNm(fileVO.getStoredFileNm());
fileInfo.setFilePath(fileVO.getFilePath());
fileInfo.setFileSize(fileVO.getFileSize());
fileInfo.setFileExt(fileVO.getFileExt());
// 실제 파일 삭제
fileUtil.deleteFile(fileInfo);
}
return result;
}
/**
* .
*
* @param fileId ID
* @param request HTTP
* @param response HTTP
*/
@Override
public void downloadCrdnFile(String fileId, HttpServletRequest request, HttpServletResponse response) {
// 파일 정보 조회
CrdnFileVO fileVO = crdnFileMapper.selectCrdnFile(fileId);
if (fileVO == null) {
throw new RuntimeException("파일 정보를 찾을 수 없습니다: " + fileId);
}
// FileVO로 변환
FileVO fileInfo = new FileVO();
fileInfo.setOriginalFileNm(fileVO.getOriginalFileNm());
fileInfo.setStoredFileNm(fileVO.getStoredFileNm());
fileInfo.setFilePath(fileVO.getFilePath());
fileInfo.setFileSize(fileVO.getFileSize());
fileInfo.setFileExt(fileVO.getFileExt());
// ContentType 설정 (파일 확장자에 따라 MIME 타입 추정)
String fileExt = fileVO.getFileExt().toLowerCase();
String contentType = FileContentTypeConstants.getContentType(fileExt);
fileInfo.setContentType(contentType);
// FileUtil을 사용하여 파일 다운로드
try {
fileUtil.downloadFile(fileInfo, request, response);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

@ -145,7 +145,7 @@ file:
path: d:/data/@projectName@/file
max-size: 10 # 단일 파일 최대 크기 (MB)
max-total-size: 100 # 총 파일 최대 크기 (MB)
max-files: 20 # 최대 파일 개수
max-files: 10 # 최대 파일 개수
allowed-extensions: hwp,jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip
real-file-delete: true # 실제 파일 삭제 여부
sub-dirs:
@ -154,6 +154,7 @@ file:
html-editor: common/html_editor # HTML 에디터 파일 저장 경로
crdn-act-photo: crdn-act-photo # 단속행위 사진
crdn-actn-photo: crdn-actn-photo # 단속행위 조치 사진
crdn-file: crdn-file # 단속 첨부파일
# Juso API configuration
juso:

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="go.kr.project.crdn.crndRegistAndView.main.mapper.CrdnFileMapper">
<!-- 파일 정보 조회 -->
<select id="selectCrdnFile" parameterType="String" resultType="CrdnFileVO">
SELECT
FILE_ID,
CRDN_YR,
CRDN_NO,
ORIGINAL_FILE_NM,
STORED_FILE_NM,
FILE_PATH,
FILE_SIZE,
FILE_EXT,
REG_DTTM,
RGTR
FROM
tb_crdn_file
WHERE
FILE_ID = #{fileId}
</select>
<!-- 단속에 첨부된 파일 목록 조회 -->
<select id="selectCrdnFileList" parameterType="CrdnFileVO" resultType="CrdnFileVO">
SELECT
FILE_ID,
CRDN_YR,
CRDN_NO,
ORIGINAL_FILE_NM,
STORED_FILE_NM,
FILE_PATH,
FILE_SIZE,
FILE_EXT,
REG_DTTM,
RGTR,
CASE
WHEN FILE_SIZE > 1048576 THEN CONCAT(ROUND(FILE_SIZE/1048576, 2), ' MB')
WHEN FILE_SIZE > 1024 THEN CONCAT(ROUND(FILE_SIZE/1024, 2), ' KB')
ELSE CONCAT(FILE_SIZE, ' bytes')
END AS FILE_SIZE_STR
FROM
tb_crdn_file
WHERE
CRDN_YR = #{crdnYr}
AND CRDN_NO = #{crdnNo}
ORDER BY
REG_DTTM DESC
</select>
<!-- 파일 ID 생성 -->
<select id="generateFileId" resultType="String">
SELECT CONCAT('CRDF', LPAD(NEXTVAL(seq_crdn_file_id), 16, '0'))
</select>
<!-- 파일 정보 등록 -->
<insert id="insertCrdnFile" parameterType="CrdnFileVO">
INSERT INTO tb_crdn_file (
FILE_ID,
CRDN_YR,
CRDN_NO,
ORIGINAL_FILE_NM,
STORED_FILE_NM,
FILE_PATH,
FILE_SIZE,
FILE_EXT,
REG_DTTM,
RGTR
) VALUES (
#{fileId},
#{crdnYr},
#{crdnNo},
#{originalFileNm},
#{storedFileNm},
#{filePath},
#{fileSize},
#{fileExt},
NOW(),
#{rgtr}
)
</insert>
<!-- 단속에 첨부된 파일 정보 삭제 -->
<delete id="deleteCrdnFileByCrdn" parameterType="CrdnFileVO">
DELETE FROM
tb_crdn_file
WHERE
CRDN_YR = #{crdnYr}
AND CRDN_NO = #{crdnNo}
</delete>
<!-- 파일 정보 삭제 -->
<delete id="deleteCrdnFile" parameterType="String">
DELETE FROM
tb_crdn_file
WHERE
FILE_ID = #{fileId}
</delete>
</mapper>

@ -22,7 +22,7 @@
<li class="tit">기본정보</li>
</ul>
<form id="crdnForm" name="crdnForm">
<form id="crdnForm" name="crdnForm" enctype="multipart/form-data">
<input type="hidden" id="mode" name="mode" value="U" />
<input type="hidden" id="crdnYr" name="crdnYr" value="${crdnYr}" />
<input type="hidden" id="crdnNo" name="crdnNo" value="${crdnNo}" />
@ -84,10 +84,50 @@
</tr>
<tr>
<th class="th">비고</th>
<td colspan="7">
<td colspan="5">
<textarea id="rmrk" name="rmrk" class="textarea" rows="1" maxlength="1000" style="width: 100%; height: 60px;"></textarea>
</td>
</tr>
<tr>
<th class="th">첨부파일 추가</th>
<td colspan="5">
<div class="file-upload-container">
<div class="file-upload-header">
<div class="file-upload-info">
<i class="material-icons">attach_file</i>
<span>최대 ${maxFiles}개의 파일을 첨부할 수 있습니다.</span>
</div>
<button type="button" id="btnAddFile" class="newbtn bg2">
<i class="material-icons">add</i>
<span>파일 추가</span>
</button>
</div>
<div id="dynamic_file_list" class="file-upload-list">
<!-- 동적으로 파일 입력 필드가 추가됩니다 -->
</div>
<c:if test="${not empty crdnFileList}">
<div class="file-list-container">
<h4 class="file-list-title">첨부된 파일 목록</h4>
<ul class="file-list">
<c:forEach var="file" items="${crdnFileList}">
<li class="file-item">
<div class="file-info">
<i class="material-icons">insert_drive_file</i>
<a href="#" class="file-name file-download-link" data-file-id="${file.fileId}">${file.originalFileNm}</a>
<span class="file-size">(${file.fileSizeStr != null ? file.fileSizeStr : file.fileSize += ' bytes'})</span>
</div>
<button type="button" class="btn_delete_file" data-file-id="${file.fileId}" title="파일 삭제">
<i class="material-icons">delete</i>
</button>
</li>
</c:forEach>
</ul>
</div>
</c:if>
</div>
</td>
</tr>
</table>
</form>
</div>
@ -261,30 +301,24 @@
var self = this;
if (!this.validate()) return;
// 폼 데이터 수집
var formData = {
crdnYr: $('#crdnYr').val(),
crdnNo: $('#crdnNo').val(),
rgnSeCd: $('#rgnSeCd').val(),
dsclMthdCd: $('#dsclMthdCd').val(),
dsclYmd: $('#dsclYmd').val().replace(/-/g, ''),
exmnr: $('#exmnr').val(),
relevyYn: $('#relevyYn').val(),
agrvtnLevyTrgtYn: $('#agrvtnLevyTrgtYn').val(),
rmrk: $('#rmrk').val()
};
// FormData 사용 (파일 업로드 지원)
var formData = new FormData(document.getElementById('crdnForm'));
if (confirm('단속 정보를 저장하시겠습니까?')) {
$.ajax({
url: '<c:url value="/crdn/crndRegistAndView/update.ajax"/>',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
if (response && response.success) {
alert('단속 정보가 성공적으로 저장되었습니다.');
// 현재 데이터 업데이트
self.currentData = formData;
// 동적으로 추가된 파일 입력 필드 초기화
$('#dynamic_file_list').empty();
// 파일 목록 새로고침
self.loadFileList();
// 그리드 새로고침
self.refreshAllGrids();
} else {
@ -306,12 +340,12 @@
if (isValid) {
// 지역구분 검증
if (!$.trim($('#rgnSeCd').val())) {
/*if (!$.trim($('#rgnSeCd').val())) {
var rgnSeElement = document.getElementById('rgnSeCd');
errorElementCreate(rgnSeElement, '지역구분을 선택하세요.', false);
$('#rgnSeCd').focus();
return false;
}
}*/
// 적발방법 검증
if (!$.trim($('#dsclMthdCd').val())) {
@ -323,12 +357,12 @@
// 재부과여부 검증
if (!$.trim($('#relevyYn').val())) {
/*if (!$.trim($('#relevyYn').val())) {
var relevyElement = document.getElementById('relevyYn');
errorElementCreate(relevyElement, '재부과여부를 선택하세요.', false);
$('#relevyYn').focus();
return false;
}
}*/
// 비고 글자수 검증 (varchar(1000) 제한)
var rmrk = $.trim($('#rmrk').val());
@ -496,6 +530,39 @@
}
});
// 파일 삭제 버튼 클릭 이벤트 (기존 파일)
$(document).on('click', '.btn_delete_file', function(event) {
// 이벤트 버블링 방지 - 파일 입력 필드 클릭 이벤트가 실행되지 않도록 함
event.stopPropagation();
event.preventDefault();
var fileId = $(this).data('file-id');
if (fileId) {
// 기존 파일 삭제
self.deleteFile(fileId);
} else {
// 새로 추가된 파일 입력 필드 삭제
$(this).closest('.file-input-row').remove();
self.updateFileCount();
}
});
// 파일 추가 버튼 클릭 이벤트
$('#btnAddFile').on('click', function() {
self.addFileInput();
});
// 파일 다운로드 클릭 이벤트 (동적으로 추가된 요소에 대응)
$(document).on('click', '.file-download-link', function(event) {
event.preventDefault();
event.stopPropagation();
var fileId = $(this).data('file-id');
if (fileId) {
self.downloadFile(fileId);
}
});
},
/**
@ -550,21 +617,231 @@
}
},
/**
* 파일 입력 필드 추가
*/
addFileInput: function() {
var self = this;
// 현재 파일 입력 필드 개수 확인
var currentFileCount = $('.file-input-row').length,
// 기존 첨부 파일 개수 확인 (수정 모드일 경우)
existingFileCount = $('.file-item').length,
maxFiles = parseInt('${maxFiles}', 5);
// 최대 파일 개수 제한 (기존 파일 + 새 파일)
if (currentFileCount + existingFileCount >= maxFiles) {
alert('최대 ' + maxFiles + '개의 파일만 첨부할 수 있습니다. (현재 기존 파일 ' + existingFileCount + '개)');
return;
}
// 파일 입력 필드 생성
var fileInputHtml =
'<div class="file-input-row">' +
' <input type="file" name="files" class="file_input" />' +
' <span class="file-input-text">파일을 선택하세요</span>' +
' <button type="button" class="btn_delete_file" title="파일 삭제">' +
' <i class="material-icons">close</i>' +
' </button>' +
'</div>';
// 파일 입력 필드 추가
var $newFileRow = $(fileInputHtml);
$('#dynamic_file_list').append($newFileRow);
// 파일 선택 이벤트 핸들러 추가
$newFileRow.find('.file_input').on('change', function() {
self.handleFileSelect(this);
});
// 파일 개수 업데이트
this.updateFileCount();
},
/**
* 파일 개수 업데이트
*/
updateFileCount: function() {
var currentFileCount = $('.file-input-row').length,
// 기존 첨부 파일 개수 확인 (수정 모드일 경우)
existingFileCount = $('.file-item').length,
maxFiles = parseInt('${maxFiles}', 5);
// 파일 추가 버튼 활성화/비활성화 (기존 파일 + 새 파일)
if (currentFileCount + existingFileCount >= maxFiles) {
$('#btnAddFile').addClass('disabled').prop('disabled', true);
} else {
$('#btnAddFile').removeClass('disabled').prop('disabled', false);
}
},
/**
* 파일 선택 처리
* 선택된 파일명을 화면에 표시합니다.
*
* @param {HTMLInputElement} fileInput 파일 입력 요소
*/
handleFileSelect: function(fileInput) {
var $fileInput = $(fileInput);
var $fileRow = $fileInput.closest('.file-input-row');
var $fileText = $fileRow.find('.file-input-text');
// 선택된 파일이 있는지 확인
if (fileInput.files && fileInput.files.length > 0) {
var fileName = fileInput.files[0].name;
var fileSize = fileInput.files[0].size;
// 파일 크기를 읽기 쉬운 형태로 변환
var fileSizeText = this.formatFileSize(fileSize);
// 파일명과 크기를 표시
$fileText.html('<i class="material-icons" style="font-size: 16px; margin-right: 5px;">insert_drive_file</i>' +
'<span style="color: #333; font-weight: 500;">' + fileName + '</span>' +
'<span style="color: #666; font-size: 12px; margin-left: 8px;">(' + fileSizeText + ')</span>');
$fileText.attr('title', fileName);
} else {
// 파일이 선택되지 않은 경우 기본 텍스트 표시
$fileText.text('파일을 선택하세요');
$fileText.removeAttr('title');
}
},
/**
* 파일 크기를 읽기 쉬운 형태로 변환
*
* @param {number} bytes 파일 크기 (바이트)
* @returns {string} 변환된 파일 크기 문자열
*/
formatFileSize: function(bytes) {
if (bytes === 0) return '0 Bytes';
var k = 1024;
var sizes = ['Bytes', 'KB', 'MB', 'GB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
},
/**
* 파일 목록 로딩
*/
loadFileList: function() {
var self = this;
var crdnYr = '${crdnYr}';
var crdnNo = '${crdnNo}';
$.ajax({
url: '<c:url value="/crdn/crndRegistAndView/fileList.ajax"/>',
type: 'GET',
data: {
crdnYr: crdnYr,
crdnNo: crdnNo
},
success: function(response) {
if (response && response.success) {
self.renderFileList(response.data);
}
}
});
},
/**
* 파일 목록 렌더링
*/
renderFileList: function(fileList) {
var $container = $('.file-list-container');
if (!fileList || fileList.length === 0) {
$container.remove();
return;
}
var html = '<div class="file-list-container">' +
'<h4 class="file-list-title">첨부된 파일 목록</h4>' +
'<ul class="file-list">';
for (var i = 0; i < fileList.length; i++) {
var file = fileList[i];
html += '<li class="file-item">' +
' <div class="file-info">' +
' <i class="material-icons">insert_drive_file</i>' +
' <a href="#" class="file-name file-download-link" data-file-id="' + file.fileId + '">' + file.originalFileNm + '</a>' +
' <span class="file-size">(' + (file.fileSizeStr || (file.fileSize + ' bytes')) + ')</span>' +
' </div>' +
' <button type="button" class="btn_delete_file" data-file-id="' + file.fileId + '" title="파일 삭제">' +
' <i class="material-icons">delete</i>' +
' </button>' +
'</li>';
}
html += '</ul></div>';
// 기존 파일 목록 제거 후 새로 추가
$container.remove();
$('.file-upload-list').after(html);
// 파일 개수 업데이트
this.updateFileCount();
},
/**
* 파일 삭제
*
* @param {string} fileId 삭제할 파일 ID
*/
deleteFile: function(fileId) {
var self = this;
if (confirm('파일을 삭제하시겠습니까?')) {
$.ajax({
url: '<c:url value="/crdn/crndRegistAndView/deleteFile.ajax" />',
type: 'POST',
data: { fileId: fileId },
success: function(response) {
if (response.success) {
alert('파일이 성공적으로 삭제되었습니다.');
// 파일 목록에서 해당 파일 항목 제거
$('[data-file-id="' + fileId + '"]').closest('li').remove();
// 파일 개수 업데이트 및 파일 추가 버튼 상태 갱신
self.updateFileCount();
} else {
alert(response.message || '파일 삭제에 실패했습니다.');
}
},
error: function(xhr, status, error) {
// 에러 처리는 xit-common.js의 ajaxError에서 처리됨
}
});
}
},
/**
* 파일 다운로드
*
* @param {string} fileId 다운로드할 파일 ID
*/
downloadFile: function(fileId) {
var downloadUrl = '<c:url value="/crdn/crndRegistAndView/download.do" />?fileId=' + encodeURIComponent(fileId);
window.location.href = downloadUrl;
},
/**
* 모듈 초기화
*/
init: function() {
var self = this;
// 중요로직: 소유자 선택/제거 버튼 초기 비활성화 설정
this.updateOwnrButtonsState(false);
// 이벤트 핸들러 설정
this.eventBindEvents();
// 단속 데이터 로딩
this.loadCrdnData();
// 파일 목록 로딩
this.loadFileList();
// 팝업에서 선택된 조사원 정보 수신 콜백 설정 (한글 주석: 팝업 → 부모창 데이터 전달 수신)
window.onExmnrSelected = function(selectedExmnrs) {
if (selectedExmnrs && selectedExmnrs.length > 0) {

Loading…
Cancel
Save