이미지 업로드 기능은 웹 애플리케이션에서 흔히 사용되는 기능으로, 사용자가 파일을 서버에 전송할 수 있도록 해줍니다. 다음은 JSP 페이지와 Struts 프레임워크를 이용한 이미지 업로드 및 다중 업로드 구현 방법입니다.
단일 이미지 업로드
JSP 페이지에서 사용자가 선택한 이미지를 서버에 저장하는 로직은 다음과 같습니다:
public boolean processImageUpload(TBasePhotoAttach attachment) throws Exception {
// 허용된 이미지 형식만 처리
if (!"image/jpeg".equals(upload1ContentType)
&& !"image/gif".equals(upload1ContentType)
&& !"image/pjpeg".equals(upload1ContentType)) {
return false;
}
// 파일 이름과 확장자 추출
String fileName = upload1FileName.substring(0, upload1FileName.lastIndexOf("."));
String extension = upload1FileName.substring(upload1FileName.lastIndexOf(".") + 1);
// 고유한 파일명 생성
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssSSS");
String uniqueName = formatter.format(new Date()) + "." + extension;
// 업로드 경로 설정
String uploadDirectory = this.getRequest().getRealPath("/") + "uploadImages";
File directory = new File(uploadDirectory);
if (!directory.exists()) {
directory.mkdirs();
}
String filePath = uploadDirectory + "\\" + uniqueName;
// 파일 저장
try (FileInputStream input = new FileInputStream(upload1);
FileOutputStream output = new FileOutputStream(filePath, false)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.read(buffer)) > 0) {
output.write(buffer, 0, bytesRead);
}
}
// DB에 정보 저장
String imageUrl = this.getRequest().getContextPath() + "/uploadImages/" + uniqueName;
attachment.setPhotoUrl(imageUrl);
attachment.setOriginalName(upload1FileName);
attachment.setUniqueName(uniqueName);
stuService.savePhoto(attachment);
return true;
}
다중 이미지 업로드
다음은 여러 파일을 한 번에 업로드하는 기능입니다:
public void handleMultipleImageUpload() throws Exception {
String uploadDirectory = this.getRequest().getRealPath("/") + "uploadImages";
File directory = new File(uploadDirectory);
if (!directory.exists()) {
directory.mkdirs();
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssSSS");
for (int index = 0; index < group.size(); index++) {
try (FileInputStream input = new FileInputStream(group.get(index))) {
String fileName = groupFileName.get(index);
String extension = fileName.substring(fileName.lastIndexOf("."));
String filePath = uploadDirectory + File.separator + formatter.format(new Date()) + extension;
try (FileOutputStream output = new FileOutputStream(filePath, false)) {
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
}
}
}
}
다음은 클라이언트 측에서 동적으로 파일 입력 필드를 추가하는 JavaScript 코드입니다:
function addMoreFiles() {
$("#upload").append("<input type='file' name='group'>");
}
<form action="<%=path%>/test/test!handleMultipleImageUpload.action" method="post" enctype="multipart/form-data">
<div id="upload">
<input type="file" name="group" label="파일 1">
</div>
<input type="button" value="더 추가" onclick="addMoreFiles();">
<input type="submit" value="전송">
</form>
jQuery 플러그인을 활용한 다중 업로드
jQuery MultiFile 플러그인을 사용하면 사용자가 쉽게 여러 파일을 선택하고 업로드할 수 있습니다. 다음과 같은 스크립트를 포함합니다:
<script src="<%=jsRoot %>/jquery/jquery.MultiFile.js" type="text/javascript" language="javascript"></script>
업로드된 파일 미리보기를 위한 JavaScript 코드는 다음과 같습니다:
function showPreview() {
var path = $("#upload1").val();
var ext = path.substr(path.indexOf(".") + 1);
if ("jpg" == ext || "png" == ext || "bmp" == ext || "jpeg" == ext) {
$("#preview img").attr("src", path);
$("#preview").show();
} else {
alert("지원되지 않는 이미지 형식입니다.");
return;
}
}
$(function() {
var photoUrl = $("#photourl").val();
if (!photoUrl || photoUrl === "") {
$("#preview").hide();
}
});
function removeAttachment(id) {
$("#" + id).remove();
var hiddenInput = "<input name='deletePhotoIds' type='hidden' value='" + id + "'/>";
$("#deleteAttachDiv").append(hiddenInput);
}
다음은 실제 폼 구조 예시입니다:
사진 업로드
/student/student!savePreparePhoto.action"
method="post" onsubmit="return checkform();" enctype="multipart/form-data" target="actionframe2">
삭제
${oldname}