파일 업로드 (1)

💻 Programming/JSP

[JSP] File Upload ( 파일 업로드 )

파일 업로드 폼 만들기

 

다음에 볼 HTML 코드가 바로 파일 업로드 폼입니다. 여기서 중요한 점을 몇가지 짚고 넘어가겠습니다.

  • <form>의 method 속성은 POST 입니다. 

  • <form>의 enctype 속성은 multipart/form-data 입니다. 

  • <form>의 action 속성은 백엔드 쪽에서 파일 업로드를 핸들링할 JSP 파일입니다. 아래 예제는 UploadFile.jsp를 사용했습니다.

  • 한개의 파일만 업로드 할 때는  <input .../> 태그를 type="file" 속성고 함께 사용합니다. 멀티플 파일업로딩을 구현하려면 하나 이상의 input태그를 각기 다른 name으로 설정해줘야 합니다.  

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

위 소스를 UploadFile.htm에 넣어주세요. 위 페이지를 출력해보면 아래처럼 나올거에요. 파일을 업로드 해보세요 ^___^ 참고로 위 코드는 그냥 dummy코드라서 실제로 파일을 어딘가로 업로드 하지는 않습니다. 

 
 

백엔드 JSP 스크립트 만들기

 

우선 파일들이 업로드되었을 때 어디에 저장될지 경로를 지정해볼게요. 경로를 지정하는 방법은 소스에 하드코딩하는 방법도 있고 web.xml파일에 context-param 태그내에 지정해주는 방법도 있습니다.

<web-app> .... <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:\apache-tomcat-5.5.29\webapps\data\ </param-value> </context-param> .... </web-app>

아래는 한번에 여러개의 파일을 업로드 할 수 있는 UploadFile.jsp의 소스코드에요. 소스부터 보기전에 점검해야할 것들이 있습니다. 

  • 아래 예제는 FileUpload 클래스를 사용하기 때문에 최신버전의 commons-fileupload.x.x.jar 파일을 클래스패스에 넣어주셔야 합니다. 여기서 http://commons.apache.org/fileupload/ 다운로드 받으실 수 있어요. 

  • 또한 Commons IO 라이브러리도 필요합니다.  commons-io-x.x.jar 파일 역시 클래스 패스에 설정을 해주셔야 되요. 다운로드는 http://commons.apache.org/io/.

  • 아래 예제를 테스트할 때에는 maxFileSize 에 설정된 파일크기보다 작은 파일들만 업로드가 가능하답니다.

  • c:\temp 와 c:\apache-tomcat-5.5.29\webapps\data 디렉토리가 있는지 확인하시고 없으면 생성해주세요. 
     

<%@ 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>"); } %>

이제 http://localhost:8080/UploadFile.htm 에 접속해서 테스트 해볼까요? 

 

제대로 작동한다면  c:\apache-tomcat-5.5.29\webapps\data\ 디렉토리에 파일이 업로드 되어있을 거에요~ 

 

 

 

Reference : http://www.tutorialspoint.com/jsp/jsp_file_uploading.htm