웹 개발에서 사용자가 파일을 첨부하고 저장하면, 이를 DB에 직접 저장(BLOB)하거나 서버에 저장하고 경로만 DB에 저장하는 방식이 있습니다. 이번 글에서는 파일을 DB에 BLOB 형태로 저장하는 방법을 jQuery와 Spring Framework 기반으로 소개합니다. 파일 백업과 보안이 중요한 시스템에 적합한 구조입니다.
1. jQuery: 첨부파일 업로드 폼
아래 코드는 사용자가 파일을 선택하고 서버에 전송하는 HTML + jQuery 폼입니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>파일 업로드</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>첨부파일 업로드 (DB BLOB 저장)</h2>
<form id="uploadForm">
<input type="file" id="fileInput" name="file" required><br><br>
<button type="button" id="uploadBtn">업로드</button>
</form>
<script>
$('#uploadBtn').click(function () {
var formData = new FormData();
formData.append("file", $('#fileInput')[0].files[0]);
$.ajax({
url: '/upload-blob',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
alert(response);
},
error: function () {
alert("업로드 실패");
}
});
});
</script>
</body>
</html>
2. Java Controller: 파일 수신 및 DB 저장
@PostMapping("/upload-blob")
@ResponseBody
public String uploadBlob(@RequestParam("file") MultipartFile file) {
try {
FileEntity fileEntity = new FileEntity();
fileEntity.setFileName(file.getOriginalFilename());
fileEntity.setContentType(file.getContentType());
fileEntity.setData(file.getBytes()); // BLOB 저장
fileRepository.save(fileEntity);
return "파일이 성공적으로 DB에 저장되었습니다.";
} catch (IOException e) {
return "업로드 실패: " + e.getMessage();
}
}
3. vo 설정 : BLOB 필드 정의
public class FileVO {
private String fileId;
private String fileName;
private byte[] fileData; // BLOB 데이터
}
4. INSERT SQL 쿼리 예시
직접 쿼리로 넣는다면 아래처럼 PreparedStatement를 사용합니다:
INSERT INTO file_entity (file_name, content_type, data)
VALUES (?, ?, ?);
마무리
BLOB 방식은 파일을 외부 경로 없이 데이터베이스에 안전하게 저장할 수 있는 장점이 있습니다. 반면, 대용량 파일이 많은 경우 성능과 저장 용량 이슈가 발생할 수 있으니 용도에 따라 적절히 선택해야 합니다. 위 예제는 보안이 중요한 인트라넷, 전자결재, 이력서 등록 시스템 등에 특히 유용합니다.