JSP 파일 업로드 및 다운로드
⚡ 스마트 요약
JSP 파일 업로드 및 다운로드는 웹 애플리케이션이 사용자로부터 파일을 받아 다시 사용자에게 제공할 수 있도록 하는 핵심 입력 및 출력 작업입니다. 이 자료에서는 JSP 액션 폼, Apache Commons FileUpload 라이브러리, 그리고 서블릿 클래스를 사용하여 두 가지 흐름을 모두 설명하고, 완벽하게 작동하는 코드를 제공합니다.

JSP 파일 업로드
- JSP를 사용하여 모든 파일을 업로드할 수 있습니다.
- 텍스트 파일, 바이너리 파일, 이미지 파일 또는 기타 문서일 수 있습니다.
- 여기서 파일 업로드의 경우 GET 방식이 아닌 POST 방식만 사용됩니다.
- Enctype 속성은 multipart/form-data로 설정되어야 합니다.
예: 작업 사용
이 예제에서는 IO 객체를 사용하여 파일을 업로드합니다.
Action_file.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru File</title> </head> <body> <a>Guru File Upload:</a> Select file: <br /> <form action="action_file_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>
Action_file_upload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ 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.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru File Upload</title> </head> <body> <% File file ; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = "E:/guru99/data"; 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(); out.println("<html>"); out.println("<body>"); 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(); file = new File( filePath + "yourFileName") ; 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("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } %> </body> </html>
코드 설명:
Action_file.jsp
Code 12-18행: 여기서는 파일을 서버에 업로드하는 파일 필드가 있는 폼을 만들고 있으며, 해당 작업은 action_file_upload.jsp로 전달됩니다.
Action_file_upload.jsp
Code 20 라인 : 여기서는 특정 경로에 대한 파일 경로를 지정하고 있습니다.
Code 23-38행: 여기서는 콘텐츠 유형이 multipart/form-data인지 확인합니다. 만약 그렇다면 콘텐츠는 파일 유형이므로 파일을 읽습니다. 파일을 읽은 후에는 임시 파일에 기록하고, 그 후 임시 파일을 메인 파일로 변환합니다.
위 코드를 실행하면 다음과 같은 출력이 나옵니다.
출력:
저희는 '파일 선택' 버튼 옵션을 사용하여 파일을 업로드하고 있으며, '파일 업로드' 버튼을 클릭하면 지정된 경로의 서버가 실행됩니다.
예: JSP 작업 사용
이 예제에서는 JSP 작업을 사용하여 파일을 업로드하는 방법을 살펴보겠습니다. "업로드" 버튼이 있는 폼을 만들고, 이 버튼을 클릭하면 파일이 업로드되도록 하겠습니다.
Uploading_1.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru Uploading File</title> </head> <body> File: <br /> <form action="guru_upload" method="post" enctype="multipart/form-data"> <input type="file" name="guru_file" size="50" /> <br /> <input type="submit" value="Upload" /> </form> </body> </html>
코드 설명:
Code 11-12행: 여기서는 guru_upload 서블릿을 호출하는 액션을 가진 폼을 사용하는데, 이 액션은 POST 메서드를 통해 데이터를 전송합니다. 또한, enctype 속성은 폼 데이터가 서버로 전송될 때 어떤 방식으로 인코딩되어야 하는지를 지정하며, POST 메서드에서만 사용됩니다. 여기서는 파일 형식(데이터 용량이 클 수 있음)에 맞춰 multipart/form-data로 설정했습니다.
Code 13 라인 : 여기서는 guru_file 요소를 파일 유형으로 지정하고 크기를 50으로 지정하고 있습니다.
Code 15 라인 : 이것은 "업로드"라는 이름의 제출 유형 버튼으로, 이 버튼을 클릭하면 액션 서블릿이 호출되어 요청이 처리되고, 파일이 서블릿에서 읽히고 기록됩니다.
Guru_업로드.java
package demotest; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class guru_upload extends HttpServlet { private static final long serialVersionUID = 1L; public guru_upload() { super(); // TODO Auto-generated constructor stub } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(ServletFileUpload.isMultipartContent(request)){ try { List <FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for(FileItem item : multiparts){ if(!item.isFormField()){ String name = new File(item.getName()).getName(); item.write( new File("c:/guru/upload" + File.separator + name)); } } //File uploaded successfully request.setAttribute("gurumessage", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("gurumessage", "File Upload Failed due to " + ex); } }else{ request.setAttribute("gurumessage","No File found"); } request.getRequestDispatcher("/result.jsp").forward(request, response); } }
코드 설명:
Code 12-14행: 여기서는 org.apache.commons 라이브러리를 코드 구성에 추가해야 합니다. 또한 org.apache.commons 라이브러리에서 fileupload 클래스를 가져와야 합니다.
Code 23 라인 : 여기에는 doPost() 메서드가 있습니다. 이 메서드는 JSP에서 POST 메서드를 전달할 때 호출되며, 요청 및 응답 객체를 매개변수로 받습니다.
Code 26 라인 : 여기서는 org.apache.commons 라이브러리의 fileUpload 패키지에 있는 ServletFileUpload 클래스의 객체를 생성합니다. 이 객체는 JSP에 파일 객체가 있는지 확인하고, 있다면 해당 파일 객체를 요청에서 가져옵니다.
Code 27-32행: 여러 파일을 업로드하는 경우, multiparts 객체(리스트 객체)에 있는 파일 항목 수를 확인하여 파일 개수만큼 반복하고, 제공된 파일 이름으로 c:/guru/upload 폴더에 저장합니다. 파일 객체의 write 메서드를 사용하여 지정된 폴더에 파일을 기록합니다.
Code 34 라인 : 예외가 발생하지 않으면 요청에 "파일이 성공적으로 업로드되었습니다"라는 값을 가진 속성을 gurumessage로 설정합니다.
Code 35-36행: 예외가 발생하면 "파일 업로드 실패"라는 메시지를 표시합니다.
Code 40 라인 : 파일을 찾을 수 없는 경우 "파일을 찾을 수 없습니다"라는 메시지를 표시합니다.
Code 42 라인 : requestDispatcher 객체를 사용하여 요청 및 응답 객체와 함께 요청을 result.jsp로 전달합니다.
결과.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Guru Result</title> </head> <body> <% String msg = (String)request.getAttribute("message"); out.println(msg); %> </body> </html>
코드 설명:
Code 10 라인 : 여기서는 요청 객체에서 "gurumessage" 값을 가진 속성을 가져와 문자열 객체로 변환합니다.
Code 11 라인 : 여기서 우리는 그 메시지를 인쇄하고 있습니다.
위 코드를 실행하면 다음과 같은 출력이 나옵니다.
출력:
디렉토리에서 파일을 선택할 수 있는 입력란이 있는 양식이 나타납니다. 파일을 선택한 후에는 업로드 버튼을 클릭해야 합니다.
업로드 버튼을 클릭하면 파일이 성공적으로 업로드되었다는 메시지가 표시됩니다.
아래 다이어그램에서 파일이 c:/guru/upload 폴더에 업로드된 것을 확인할 수 있습니다.
JSP 파일 다운로드
이 예에서는 버튼을 클릭하여 디렉터리에서 파일을 다운로드하겠습니다.
Download_1.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Downloading Guru Example</title> </head> <body> Guru Downloading File<a href="guru_download">Download here!!!</a> </body> </html>
코드 설명:
Code 10 라인 : 여기서는 guru_download 서블릿을 사용하여 c:/guru/upload 폴더에서 파일을 다운로드하는 링크를 제공합니다.
Guru_다운로드.java
package demotest; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class guru_download */ public class guru_download extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String gurufile = "test.txt"; String gurupath = "c:/guru/upload/"; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=\"" + gurufile + "\""); FileInputStream fileInputStream = new FileInputStream(gurupath + gurufile); int i; while ((i = fileInputStream.read()) != -1) { out.write(i); } fileInputStream.close(); out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
코드 설명:
Code 3-5행: 여기서는 FileInputStream, IOException 및 Print를 임포트합니다.Writer java.io 패키지에서 가져온 것입니다.
Code 15 라인 : 우리는 guru_download를 정의하고 있습니다. 서블릿 이는 HttpServlet을 확장합니다.
Code 18 라인 : 우리는 href를 정의했고, 이는 <a> 태그 안에 포함될 것입니다. URL따라서 GET 메서드가 처리되고(서블릿에서 doGet이 호출됨), 요청 및 응답 객체가 포함됩니다.
Code 19-20행: 응답 객체에 콘텐츠 유형을 설정하고 응답에서 작성자 객체도 가져옵니다.
Code 21-22행: gurufile이라는 변수를 정의하고 값을 test.txt로, gurupath를 c:/guru/upload/로 지정합니다.
Code 23-25행: 응답 객체를 사용하여 콘텐츠 유형을 설정하고, setHeader 메서드를 사용하여 업로드된 파일 이름을 응답 객체의 헤더에 설정합니다.
Code 27-28행: gurupath+gurufile을 추가할 FileInputStream을 생성하고 있습니다.
Code 31-33행: 여기서 우리는 while 루프 이 코드는 파일 읽기가 완료될 때까지 실행되므로 조건을 != -1로 설정했습니다. 이 조건에서는 printwriter 객체를 사용하여 출력합니다.
위 코드를 실행하면 다음과 같은 출력이 나타납니다.
출력:
downloading_1.jsp 파일을 클릭하면 "여기서 다운로드"라는 하이퍼링크가 생성됩니다. 이 하이퍼링크를 클릭하면 파일이 시스템에 다운로드됩니다.





