[java] JSP에서의 파일 업로드 처리하기

웹 애플리케이션에서 파일을 업로드하는 기능은 많은 경우에 필요하게 됩니다. JSP에서는 파일 업로드를 간단하게 처리할 수 있는 방법을 제공합니다.

파일 업로드를 위한 폼 생성하기

먼저, 파일 업로드를 처리하는 JSP 페이지에서 업로드 폼을 생성해야 합니다. 아래의 예제는 파일 업로드를 위한 폼을 생성하는 코드입니다.

<form action="upload.jsp" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="업로드">
</form>

위의 코드에서 enctype="multipart/form-data"는 파일 업로드를 지원하기 위해 필요한 설정입니다. 그리고 name="file"은 업로드된 파일을 서버로 전송할 때 사용할 파라미터 이름을 정의합니다.

파일 업로드 처리하기

이제 파일 업로드를 처리하는 JSP 페이지인 upload.jsp를 작성해보겠습니다. 아래의 코드는 파일을 업로드하는 과정을 처리하는 코드입니다.

<%@ page import="java.io.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>

<%
    String saveDirectory = "경로를 입력하세요"; // 파일을 저장할 경로

    File fileSaveDir = new File(saveDirectory);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }

    // 업로드된 파일을 저장할 경로 및 파일명 설정
    String fileName = "";
    String filePath = "";
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.getInputStream());
        int formDataLength = request.getContentLength();
        byte[] dataBytes = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;

        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
            totalBytesRead += byteRead;
        }

        String file = new String(dataBytes);
        fileName = file.substring(file.indexOf("filename=\"") + 10);
        fileName = fileName.substring(0, fileName.indexOf("\n"));
        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.indexOf("\""));
        filePath = saveDirectory + File.separator + fileName;

        FileOutputStream fileOut = new FileOutputStream(filePath);
        fileOut.write(dataBytes);
        fileOut.flush();
        fileOut.close();
    }
%>

<%

    // 업로드된 파일 정보 출력
    out.println("파일 이름: " + fileName + "<br>");
    out.println("파일 경로: " + filePath + "<br>");
%>

위의 코드에서는 saveDirectory 변수에 업로드된 파일을 저장할 경로를 지정해야 합니다. 또한, 업로드된 파일의 정보(이름과 경로)는 HTML로 출력하도록 작성되어 있습니다.

정리하기

이제 JSP에서 파일 업로드를 처리하는 방법을 알게 되었습니다. 파일 업로드 폼을 생성하고 업로드되는 파일을 처리하는 JSP 페이지를 작성함으로써 웹 애플리케이션에 파일 업로드 기능을 추가할 수 있습니다.

참고 자료