본문 바로가기

jsp

파일 업로드: 웹 페이지에서 파일 업로드 기능을 구현하는 방법을 배우는 예제.

반응형

웹 페이지에서 파일을 업로드하는 것은 사용자가 서버에 데이터를 보낼 수 있게 하는 중요한 기능입니다. JSP에서 파일 업로드를 구현하려면 일반적으로 Apache Commons FileUpload 라이브러리와 같은 외부 라이브러리를 사용합니다. 여기서는 파일 업로드를 구현하는 두 가지 예제를 제공하겠습니다.

예제 1: 간단한 파일 업로드

이 예제는 HTML 폼을 사용하여 파일을 업로드하는 방법을 보여줍니다. 사용자가 파일을 선택하고 업로드 버튼을 누르면, 파일이 서버로 전송됩니다.

HTML Form (uploadForm.jsp)

<!DOCTYPE html>
<html>
<head>
    <title>Simple File Upload</title>
</head>
<body>
<form action="FileUpload.jsp" method="post" enctype="multipart/form-data">
    Select file: <input type="file" name="file">
    <input type="submit" value="Upload">
</form>
</body>
</html>

 

JSP File Upload Handler (FileUpload.jsp)

<%@ page import="java.io.*,java.util.*,javax.servlet.*,javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
<%
    // 파일이 저장될 서버의 디렉토리 경로 지정
    String filePath = getServletContext().getRealPath("/") + "uploads";

    // 파일 업로드 처리
    File file ;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    ServletContext context = pageContext.getServletContext();
    String contentType = request.getContentType();

    // 파일 데이터가 들어왔는지 확인
    if ((contentType.indexOf("multipart/form-data") >= 0)) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 최대 메모리 설정
        factory.setSizeThreshold(maxMemSize);
        // 임시 저장 위치 설정
        factory.setRepository(new File("c:\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);
        // 최대 업로드 파일 크기 설정
        upload.setSizeMax( maxFileSize );

        try {
            // 요청 파싱
            List fileItems = upload.parseRequest(request);

            // 개별 파일 처리
            Iterator i = fileItems.iterator();

            while ( i.hasNext () ) {
                FileItem fi = (FileItem)i.next();
                if ( !fi.isFormField () ) {
                    // 파일 메타데이터 추출
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    // 파일 쓰기
                    if( fileName.lastIndexOf("\\") >= 0 ) {
                        file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
                    } else {
                        file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                    }
                    fi.write( file );
                    out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                }
            }
        } catch(Exception ex) {
            System.out.println(ex);
        }
    } else {
        out.println("No file uploaded");
    }
%>
</body>
</html>

 

관련 전문용어 설명

  • Multipart/form-data: 파일 업로드를 위한 HTTP POST 요청에서 사용되는 인코딩 타입입니다. 이를 통해 사용자가 폼을 통해 전송한 데이터를 여러 파트로 나누어 서버에 전송할 수 있습니다.
  • Apache Commons FileUpload: Java를 위한 파일 업로드 라이브러리로, 복잡한 멀티파트 요청을 쉽게 처리할 수 있도록 도와줍니다.
  • DiskFileItemFactory & ServletFileUpload: Apache Commons FileUpload 라이브러리의 클래스로, 업로드 파일 데이터를 처리하고 저장하는 데 사용됩니다.
  •  
반응형