게시글 저장 시 파일 업로드
@Override
public int insertBoard(BoardListDto dto) throws Exception {
log.info("serviceImpl dto = {}", dto);
BoardListDto board = BoardListDto.builder()
.title(dto.getTitle())
.content(dto.getContent())
.files(dto.getFiles())
.uploadFileUrl(dto.getUploadFileUrl())
.commentCnt(dto.getCommentCnt())
.userId(dto.getUserId()) // 로그인한 // 이름 저장
.build();
log.info("serviceImple -> board = {}", board);
int result = boardMapper.insertBoard(board);
log.info("result = {}", result);
log.info("dto.getBoardId() = {}" , board.getBoardId());
String boardFolderPath = createFolder(path, board.getBoardId());
File file = new File(boardFolderPath);
// 경로가 없을 경우 파일을 생성
if (!file.exists()) {
file.mkdirs();
}
for (MultipartFile f : board.getFiles()) {
if (!f.isEmpty()) {
log.info("file => {}", f.getOriginalFilename());
// HDD SAVE
String fileName = fileManager.saveFile(f, boardFolderPath);
// DB SAVE
UploadFileVO uploadFileVO = UploadFileVO.builder()
.orgFileName(f.getOriginalFilename())
.saveFileName(fileName)
.savePath(boardFolderPath)
.fileSize(f.getSize())
.boardId(board.getBoardId())
.build();
boardMapper.insertFile(uploadFileVO);
}
}
return result;
}
게시글 마다 폴더 생성하여 파일을 저장
private String createFolder(String basePath, Long boardId) {
String folderPath = basePath + "/" + boardId;
File folder = new File(folderPath);
if (!folder.exists()) {
folder.mkdirs();
}
return folderPath;
}
게시글 저장 시 SelectKey 키워드를 사용하여 해당 게시글의 ID값을 DTO에 넣어서 반환함.
<!-- 게시판 글 생성 -->
<insert id="insertBoard" parameterType="boardListDto" useGeneratedKeys="true">
<![CDATA[
INSERT INTO BOARD (BOARD_ID, TITLE, CONTENT, UPLOAD_FILE_URL, COMMENT_CNT, WRITER)
VALUES (
board_seq.nextval,
#{title},
#{content, jdbcType=CLOB},
#{uploadFileUrl},
#{commentCnt},
(SELECT USER_ID
FROM USERS
WHERE USER_ID = #{userId}))
]]>
<selectKey keyProperty="boardId" resultType="long" order="AFTER">
SELECT MAX(BOARD_ID) FROM BOARD
</selectKey>
</insert>
그렇게 해두면 INSERT 이후에 바로 ID값을 가져와 다시 파일 업도르 시 활용 가능.
위에도 있는 코드지만 정확히 이렇게 꺼내서 쓸 수 있기 된다.
int result = boardMapper.insertBoard(board);
String boardFolderPath = createFolder(path, board.getBoardId());
따라서 해당 ID값을 받아서 VO 객체를 생성한 뒤 파일을 DB에 INSERT 해주면 됨.
// DB SAVE
UploadFileVO uploadFileVO = UploadFileVO.builder()
.orgFileName(f.getOriginalFilename())
.saveFileName(fileName)
.savePath(boardFolderPath)
.fileSize(f.getSize())
.boardId(board.getBoardId())
.build();
boardMapper.insertFile(uploadFileVO);
/**
* boardWrite.js
*/
function maxlengthCheck() {
var content = $('textarea#content').val();
if (content.length > 100000) {
alert("본문 내용은 100,000자 이내여야 합니다.");
return false;
}
}
$(document).ready(function() {
$('#insertBtn').click(function(event) {
event.preventDefault();
var title = $('#title').val();
var content = $('textarea#content').val();
console.log("content : ", content);
if (title.trim() === '') {
alert('제목을 입력해주세요.');
return false;
}
if (content.trim() === '') {
alert('내용을 입력해주세요.');
return false;
}
if (!confirm("저장하시겠습니까?")) {
return;
}
var form = $('#writeForm')[0];
var data = new FormData(form);
data.append('customField', '추가필드');
$('#insertBtn').prop('disabled', true);
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: "/board/write",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function(data) {
location.href = "/";
alert("저장되었습니다.");
console.log('SUCCESS : ', data);
},
error: function(e) {
console.log('ERROR : ', e);
alert("저장에 실패하였습니다.")
}
});
});
});