JSP는 HTML 폼(form) 태그와 함께 사용하여 사용자가 서버에 파일을 업로드할 수 있도록 지원합니다. 업로드 대상 파일은 텍스트 파일, 바이너리 파일, 이미지 파일 등 어떤 종류의 문서든 가능합니다.
파일 업로드 폼 만들기
먼저 파일 업로드 폼을 만드는 방법부터 살펴보겠습니다. 다음 HTML 코드는 업로더 폼을 생성하며, 작성 시 아래의 중요 사항들을 반드시 유의해야 합니다.
- 폼의 method 속성은 반드시 POST 방식으로 설정해야 하며, GET 방식은 사용할 수 없습니다.
- 폼의 enctype 속성은 반드시 multipart/form-data로 지정해야 합니다.
- 폼의 action 속성은 백엔드 서버에서 파일 업로드를 처리할 JSP 파일로 설정해야 합니다. 아래 예제에서는 uploadFile.jsp 파일이 이 역할을 담당합니다.
- 단일 파일을 업로드하려면 type="file" 속성을 가진 하나의 <input .../> 태그를 사용합니다. 여러 파일을 동시에 업로드하려면 name 속성 값이 서로 다른 input 태그를 여러 개 추가하면 되며, 브라우저는 각 태그마다 찾아보기(Browse) 버튼을 자동으로 연결해 줍니다.
예제 코드
<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>
위 코드를 실행하면 다음과 같은 화면이 나타납니다. 로컬 PC에서 파일을 선택한 후 "Upload File" 버튼을 클릭하면, 선택한 파일과 함께 폼이 서버로 제출됩니다.
실행 결과
File Upload Select a file to upload
참고 — 위 폼은 단순한 예시용 더미 폼으로 실제로는 동작하지 않습니다. 직접 코드를 작성하여 실행해야만 정상적으로 작동합니다.
백엔드 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 라이브러리에 의존하므로, 클래스패스(classpath)에 최신 버전의 commons-fileupload.x.x.jar 파일이 포함되어 있는지 확인하세요. https://commons.apache.org/fileupload/ 에서 다운로드할 수 있습니다.
- FileUpload는 Commons IO에 의존하므로, 최신 버전의 commons-io-x.x.jar 파일도 클래스패스에 포함되어 있어야 합니다. https://commons.apache.org/io/ 에서 다운로드할 수 있습니다.
- 예제를 테스트할 때는 maxFileSize보다 작은 크기의 파일을 업로드해야 하며, 그렇지 않으면 파일이 업로드되지 않습니다.
- c:\temp 디렉터리와 c:\apache-tomcat5.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>");
}
%>
이제 앞서 만든 HTML 폼을 통해 실제로 파일을 업로드해 보겠습니다. 브라우저에서 https://localhost:8080/UploadFile.htm에 접속하면 다음과 같은 화면이 표시되며, 로컬 컴퓨터에 있는 파일을 자유롭게 업로드할 수 있습니다.
File Upload Select a file to upload
JSP 스크립트가 오류 없이 정상적으로 실행되었다면, 업로드된 파일은 c:\apache-tomcat5.5.29\webapps\data\ 디렉터리에 저장되어 있을 것입니다. 즉, JSP에서 업로드된 파일의 저장 위치는 web.xml의 context-param 설정값에 따라 결정되며, 필요에 따라 언제든 원하는 경로로 변경할 수 있습니다.