JSP 파일 업로드 및 다운로드
이번 예제에서는 JSP를 통해 파일을 업로드하고 다운로드하는 방법을 알아보겠습니다.
파일 입력 출력은 매우 중요한 작업입니다. 여기서는 JSP를 사용하여 파일을 읽고 쓸 것입니다.
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
코드 라인 12-18: 여기서는 서버에 파일을 업로드하고 작업이 action_file_upload.jsp로 전달되는 파일 필드가 있는 양식을 생성합니다.
Action_file_upload.jsp
코드 라인 20: 여기서는 특정 경로에 대한 파일 경로를 제공합니다.
코드 라인 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>
코드 설명:
코드 라인 11-12: 여기서 우리는 서블릿 guru_upload에서 액션이 있는 폼을 가져오고, 이는 POST 메서드를 통과합니다. 또한, 여기서 우리는 폼 데이터가 어떻게 인코딩되어 서버로 전송되어야 하는지 지정하는 enctype ie 속성을 지정하고, 이는 POST 메서드에서만 사용됩니다. 여기서 우리는 파일에 대한 multipart/form-data로 설정합니다(데이터가 클 것임).
코드 라인 13: 여기서는 파일 유형으로 guru_file 요소를 지정하고 크기를 50으로 지정합니다.
코드 라인 15: 이는 작업 서블릿이 호출되고 요청이 처리되며 파일을 읽고 서블릿에 쓰는 "업로드"라는 이름의 제출 유형 버튼입니다.
Guru_upload.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); } }
코드 설명:
코드 라인 12-14: 여기서는 org.apache.commons 라이브러리를 코드 구성으로 가져와야 합니다. org.apache.commons 라이브러리에서 fileupload 클래스를 가져와야 합니다.
코드 라인 23: 여기에는 JSP에서 POST 메소드를 전달할 때 호출되는 doPost() 메소드가 있으며 매개변수로 객체를 요청하고 응답합니다.
코드 라인 26: 여기서는 JSP에 파일 객체가 있는지 확인하는 org.apache.commons 라이브러리의 fileUpload 패키지에서 ServletFileUpload 클래스 객체를 생성합니다. 발견된 경우 해당 파일 객체가 요청에서 가져옵니다.
코드 라인 27-32: 목록 객체인 multiparts 객체에 존재하는 파일 항목 수를 확인하여(두 개 이상의 파일을 업로드하는 경우) 파일 수를 반복하고 제공된 파일 이름으로 c:/guru/upload 폴더에 저장합니다. . 앞서 언급한 폴더에 fileobject의 write 메소드를 사용하여 파일을 쓰고 있습니다.
코드 라인 34: 예외가 없으면 요청의 속성을 "파일이 성공적으로 업로드되었습니다" 값을 갖는 gurumessage로 설정합니다.
코드 라인 35-36: 예외가 발생하면 "파일 업로드 실패"라는 메시지를 설정합니다.
코드 라인 40: 파일을 찾을 수 없으면 메시지를 "파일을 찾을 수 없음"으로 설정합니다.
코드 라인 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>
코드 설명:
코드 라인 10: 여기서는 gurumessage 값을 가진 요청 객체의 속성을 문자열 객체로 가져옵니다.
코드 라인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>
코드 설명:
코드 라인 10: 여기서는 서블릿 guru_download 를 사용하여 c:/guru/upload 폴더에서 파일을 다운로드할 수 있는 링크를 제공했습니다.
Guru_download.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 } }
코드 설명:
코드 라인 3-5: 여기서는 java.io 패키지에서 FileInputStream, IO Exception 및 PrintWriter를 가져옵니다.
코드 라인 15: 우리는 guru_download를 정의하고 있습니다 서블릿 이는 HttpServlet을 확장합니다.
코드 라인 18: URL에 포함될 href를 정의했으므로 GET 메소드가 처리되고(doGet은 서블릿에서 호출됨) 요청 및 응답 객체도 포함됩니다.
코드 라인 19-20: 응답 개체에 콘텐츠 유형을 설정하고 응답에서 작성자 개체도 가져옵니다.
코드 라인 21-22: 변수를 test.txt 값으로 gurufile로 정의하고 c:/guru/upload/로 gurupath를 정의합니다.
코드 라인 23-25: 응답 객체를 사용하여 콘텐츠 유형을 설정하고 업로드된 파일 이름으로 응답 객체에 헤더를 설정하는 setHeader 메소드를 사용합니다.
코드 라인 27-28: gurupath+gurufile을 추가할 FileInputStream을 생성 중입니다.
코드 라인 31-33: 여기서 우리는 while 루프 파일을 읽을 때까지 실행되므로 조건은 != -1로 지정됩니다. 이 조건에서 우리는 printwriter 객체 출력을 사용하여 쓰고 있습니다.
위 코드를 실행하면 다음과 같은 출력이 나옵니다.
출력:
출력:
downloading_1.jsp를 클릭하면 “Download Here”라는 하이퍼링크가 표시됩니다. 이 하이퍼링크 파일을 클릭하면 시스템에 다운로드됩니다.
제품 개요
- 우리는 모든 애플리케이션에 등록하기 위한 등록 양식에 대해 배웠습니다.
- 로그인 및 로그아웃 양식의 작동 방식에 대해 자세히 알아보세요.
- 또한 JSP를 통한 파일 업로드 및 다운로드에 대해서도 배웠습니다.