본문 바로가기
프로그래밍/JAVA

매우 쉬운 첨부파일 업로드 하기 JSP 예제

by 애플 로그 2021. 2. 19.
반응형

JSP 첨부파일 업로드 하기 쉬운 예제

서버에 첨부파일 업로드하는 간단한 예제를 만들어 봤습니다.

 

준비물 

apache 에서 제공하는 Liblibrary 필요

보통 왠만한 was 구성시에는 기본으로 들어가는 애들이긴 합니다.

 

아래 maven 레파지토리에서 버전 확인후 다운 가능.

 

 

1. commons-fileupload

mvnrepository.com/artifact/commons-fileupload/commons-fileupload

 

Maven Repository: commons-fileupload » commons-fileupload

The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications. VersionRepositoryUsagesDate1.4.x1.4Central247Dec, 20181.3.x1.3.3Central525Jun, 20171.3.

mvnrepository.com

2. commons-io

mvnrepository.com/artifact/commons-io/commons-io

 

Maven Repository: commons-io » commons-io

The Apache Commons IO library contains utility classes, stream implementations, file filters, file comparators, endian transformation classes, and much more. VersionRepositoryUsagesDate2.8.0Central1,410Sep, 20202.7Central1,198May, 20202.6Central5,921Oct, 2

mvnrepository.com

 

 

아래 1,2 번 파일을 동일 위치에 넣고, upload.html 페이지에서 첨부 하면 됨.

 

1. 파일 전송 페이지 - upload.html

<html>
   <head>
      <title>File Upload</title>
   </head>
   
   <body>
      <h3>File Upload:</h3>
      Select a file to upload: <br />
      <form action = "./upload.jsp" method = "post"
         enctype = "multipart/form-data">
         <input type = "file" name = "file" size = "50" />
         <br />
         <input type = "submit" value = "Upload File" />
      </form>
   </body>
   
</html>

 

 

2. 첨부파일 받는 역할 - upload.jsp 

java servlet으로 만들어도 되고, 아래처럼 그냥 jsp 형태로 써도 된다.

 

<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>

<%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
   String filePath = context.getInitParameter("file-upload");

   // Verify the content type
   String contentType = request.getContentType();
   
   if ((contentType.indexOf("multipart/form-data") >= 0)) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
      
      try { 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>JSP File upload</title>");  
         out.println("</head>");
         out.println("<body>");
         
         while ( i.hasNext () ) {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) {
               // Get the uploaded file parameters
               String fieldName = fi.getFieldName();
               String fileName = fi.getName();
               boolean isInMemory = fi.isInMemory();
               long sizeInBytes = fi.getSize();
            
               // Write the file
               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>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      } catch(Exception ex) {
         System.out.println(ex);
      }
   } else {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
%>

댓글