서블릿을 활용한 파일 업로드 구현 및 처리 방법

서블릿을 활용한 파일 업로드 구현 및 처리 방법

이번 글에서는 서블릿을 사용하여 클라이언트가 업로드한 파일을 서버에 저장하는 방법에 대해 알아보겠습니다. 파일 업로드 기능은 사용자로부터 이미지를 업로드하거나 문서를 제출받는 등 다양한 웹 애플리케이션에서 유용하게 활용됩니다.

1. 서블릿에서 파일 업로드 처리

파일 업로드를 처리하려면 먼저 서블릿에 몇 가지 설정을 추가해야 합니다. @MultipartConfig 어노테이션을 사용하여 파일 업로드에 대한 크기 제한 및 요청 크기를 정의하고, 서버에서 파일을 받아 저장하는 로직을 구성해야 합니다.

파일 업로드 처리 예제 코드

package com.bluesharehub;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@WebServlet("/upload")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2,  // 2MB
                 maxFileSize = 1024 * 1024 * 10,      // 10MB
                 maxRequestSize = 1024 * 1024 * 50)   // 50MB
public class FileUploadServlet extends HttpServlet {

    private static final String UPLOAD_DIR = "C:\\blueshare\\upload";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 인코딩 설정
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 업로드 폴더가 없으면 생성
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 업로드된 파일 처리
        for (Part part : request.getParts()) {
            String fileName = Paths.get(part.getSubmittedFileName()).getFileName().toString();
            String filePath = UPLOAD_DIR + File.separator + fileName;
            part.write(filePath);  // 파일 저장

            // 결과 출력
            response.getWriter().println("<h1>파일 업로드 성공!</h1>");
            response.getWriter().println("저장된 파일 경로: " + filePath);
        }
    }
}

코드 설명

  • @MultipartConfig: 파일 업로드 설정을 정의합니다. fileSizeThreshold는 파일이 임시 메모리에서 저장되는 크기, maxFileSize는 업로드할 수 있는 파일의 최대 크기, maxRequestSize는 전체 요청 크기의 제한을 정의합니다.
  • 업로드 경로 설정: 파일이 저장될 폴더를 지정하며, 폴더가 존재하지 않으면 자동으로 생성합니다.
  • 파일 저장: request.getParts()를 통해 클라이언트가 업로드한 파일을 받아 part.write()로 저장합니다.

2. 파일 업로드 폼

이제 클라이언트가 파일을 업로드할 수 있는 간단한 폼을 만들어보겠습니다. 아래는 JSP로 작성된 파일 업로드 폼의 예시입니다.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>파일 업로드</title>
</head>
<body>
    <h1>파일 업로드</h1>
    <form action="upload" method="post" enctype="multipart/form-data">
        <label for="file">파일 선택:</label>
        <input type="file" name="file" id="file">
        <input type="submit" value="업로드">
    </form>
</body>
</html>

3. 실행 결과

위 코드를 통해 파일을 업로드하고 서버에 저장한 후, 아래와 같이 저장된 파일 경로가 출력됩니다.

파일 업로드 성공!
저장된 파일 경로: C:\blueshare\upload\example.png

실행 결과 화면

서블릿에서 파일 업로드 처리 예제 코드 실행 결과 화면
윈도우 탐색기에서 업로드한 파일 확인 화면

결론

서블릿을 사용한 파일 업로드는 @MultipartConfig 어노테이션을 통해 쉽게 구현할 수 있습니다. 업로드된 파일은 서버에 저장되며, 파일 크기와 요청 크기 등의 제한을 설정하여 서버 리소스를 효율적으로 관리할 수 있습니다. 이 방법을 활용하면 다양한 파일 업로드 기능을 서블릿 기반의 웹 애플리케이션에 구현할 수 있습니다.

함께 보면 좋은 이전 게시글

위로 스크롤