본문 바로가기

jsp

이미지 게시판: 이미지를 업로드하고 표시하는 간단한 이미지 게시판 예제.

반응형

이미지 게시판은 사용자가 이미지를 업로드하고, 이러한 이미지들을 웹 페이지에서 볼 수 있도록 하는 시스템입니다. 일반적으로 이미지 업로드, 저장, 표시 기능을 포함합니다. JSP에서는 서블릿과 함께 파일 업로드 라이브러리(예: Apache Commons FileUpload)를 사용하여 이미지를 처리할 수 있습니다. 다음은 간단한 이미지 게시판을 구현하는 두 가지 예제입니다.

예제 1: 이미지 업로드

이 예제에서는 사용자가 이미지를 업로드할 수 있는 기능을 구현합니다.

uploadImage.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Upload Image</title>
</head>
<body>
    <h2>Image Upload</h2>
    <form action="uploadHandler.jsp" method="post" enctype="multipart/form-data">
        Select image to upload:
        <input type="file" name="file">
        <input type="submit" value="Upload Image" name="submit">
    </form>
</body>
</html>

 

uploadHandler.jsp

<%@ page import="java.io.*,org.apache.commons.fileupload.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);

        for (FileItem item : items) {
            if (!item.isFormField()) {
                // Process form file field (input type="file").
                String fileName = new File(item.getName()).getName();
                String filePath = "upload" + File.separator + fileName; // Define your path here
                File storeFile = new File(filePath);

                // Saves the file on disk
                item.write(storeFile);
                out.println("Upload has been done successfully!");
            }
        }
    } catch (Exception ex) {
        out.println("There was an error: " + ex.getMessage());
    }
%>

 

예제 2: 이미지 목록 표시

이 예제에서는 업로드된 이미지들을 웹 페이지에서 보여주는 기능을 구현합니다.

imageList.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Image List</title>
</head>
<body>
    <h2>Uploaded Images</h2>
    <% 
    File folder = new File("upload"); // The directory where images are stored
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
        out.println("<img src='upload/" + listOfFiles[i].getName() + "' style='width: 200px;'><br>");
      }
    }
    %>
</body>
</html>

 

관련 전문용어 설명

  • 멀티파트(Multipart): HTTP 프로토콜을 사용하여 웹 폼에서 파일(이미지, 비디오 등)을 업로드할 때 사용하는 메시지 형식입니다.
  • FileUpload: 파일을 웹 서버에 업로드하기 위해 사용되는 Apache Commons FileUpload 라이브러리의 컴포넌트입니다.
  • 리스트(List): Java에서 객체의 컬렉션을 저장하는데 사용되는 인터페이스 중 하나입니다.
  •  
반응형