English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Servlet은 HTML form 태그와 함께 사용하여 사용자가 서버로 파일을 업로드할 수 있게 합니다. 업로드할 수 있는 파일은 텍스트 파일이나 이미지 파일이나 어떤 문서든 될 수 있습니다.
이 문서에서 사용된 파일은 다음과 같습니다:
upload.jsp : 파일 업로드 폼
message.jsp : 업로드 성공 후 이동 페이지
UploadServlet.java : 업로드 처리 Servlet
소요되는 jar 파일: commons-fileupload-1.3.2、commons-io-2.5.jar
구조도는 다음과 같습니다:
주의:Servlet3.0은 파일 업로드 기능을 기본적으로 내장하고 있으며, 개발자는 Commons FileUpload 컴포넌트를 프로젝트에 가져오지 않아도 됩니다.
다음에 자세히 설명하겠습니다.
다음 HTML 코드는 파일 업로드 폼을 생성합니다. 다음 포인트를 주의하세요:
양식 메서드 속성은 설정되어야 합니다 POST 메서드는 GET 메서드를 사용할 수 없습니다.
양식 enctype 속성은 설정되어야 합니다 multipart/form-data.
양식 action 속성은 백엔드 서버에서 파일 업로드를 처리하는 Servlet 파일을 설정해야 합니다. 아래의 예제는 UploadServlet Servlet를 파일 업로드를 위해 사용해야 합니다.
단일 파일을 업로드하려면, type="file" 속성을 가진 단일 입력 태그를 사용해야 합니다./> 태그를 포함하여 여러 개의 파일을 업로드할 수 있도록 합니다. 다른 이름 값을 가진 여러 개의 input 태그를 포함합니다. 입력 태그는 다른 이름 값을 가진 input 태그와 연결됩니다. 브라우저는 각 input 태그에 하나의 파일 선택 버튼을 연결합니다.
upload.jsp 파일 코드는 다음과 같습니다:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> !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=UTF-8"> <title>파일 업로드 예제 - 기본 가이드 사이트</title> </head> <body> <h1>파일 업로드 예제 - 기본 가이드 사이트</h1> <form method="post" action="/TomcatTest/UploadServlet" enctype="multipart/form-data"> 파일을 선택하세요: <input type="file" name="uploadFile" /> <br/><br/> <input type="submit" value="업로드" /> </>form> </body> </html>
아래는 UploadServlet의 소스 코드입니다. 파일 업로드를 처리하는 데 사용되며, 이전에 먼저 의존성 패키지가 프로젝트의 WEB-INF/lib 디렉토리에 있습니다:
아래의 예제는 FileUpload에 의존하므로, 반드시 최신 버전의 commons-fileupload.x.x.jar 파일에서 http://commons.apache.org/proper/commons-fileupload/ 다운로드。
FileUpload는 Commons IO에 의존하므로, 반드시 최신 버전의 commons-io-x.x.jar 파일에서 http://commons.apache.org/proper/commons-io/ 다운로드。
당신은 이 사이트에서 제공하는 두 가지 의존성 패키지를 직접 다운로드할 수 있습니다:
UploadServlet의 소스 코드는 다음과 같습니다:
package com.w;3codebox.test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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; /** * Servlet 구현 클래스 UploadServlet */ @WebServlet("/UploadServlet) public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; // 업로드 파일 저장 디렉토리 private static final String UPLOAD_DIRECTORY = "upload"; // 업로드 설정 private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB /** * 데이터 업로드 및 파일 저장 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 미디어 업로드 여부 검사 (!ServletFileUpload.isMultipartContent(request)) { // 아니라면 중지}} PrintWriter writer = response.getWriter(); writer.println("Error: 表单必须包含 enctype=multipart/form-data"); writer.flush(); return; } // 업로드 매개변수 구성 DiskFileItemFactory factory = new DiskFileItemFactory(); // 메모리 임계값 설정 - 초과하면 임시 파일을 생성하여 임시 디렉토리에 저장 factory.setSizeThreshold(MEMORY_THRESHOLD); // 임시 저장 디렉토리 설정 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 최대 파일 업로드 값 설정 upload.setFileSizeMax(MAX_FILE_SIZE); // 최대 요청 값 설정 (파일과 폼 데이터 포함) upload.setSizeMax(MAX_REQUEST_SIZE); // 중국어 처리 upload.setHeaderEncoding("UTF-8); // 올라가는 파일을 저장하기 위한 일시적인 경로를 생성 // 이 경로는 현재 애플리케이션 디렉토리에 상대적입니다 String uploadPath = request.getServletContext().getRealPath("./) + File.separator + UPLOAD_DIRECTORY; // 폴더가 존재하지 않으면 생성 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // 내용을 분석하여 파일 데이터를 추출 @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // 폼 데이터를 순회합니다 for (FileItem item : formItems) { // 폼에 없는 필드 처리 if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // 컨솔에 파일 업로드 경로 출력합니다 System.out.println(filePath); // 파일을 하드디스크에 저장합니다 item.write(storeFile); request.setAttribute("message", "파일 업로드 성공!"); } } } } catch (Exception ex) { request.setAttribute("message", "에러 정보: " + ex.getMessage()); } // message.jsp로 이동합니다 message.jsp").forward(/request.getServletContext().getRequestDispatcher(" request, response); } }
message.jsp 파일 코드는 다음과 같습니다:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> !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=UTF-8"> <title>파일 업로드 결과</title> </head> <body> <center> <h2${message}</h2> </center> </body> </html>
위의 Servlet UploadServlet을 컴파일하고 web.xml 파일에서 필요한 항목을 다음과 같이 생성하세요:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.w3codebox.test.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/TomcatTest/UploadServlet</url-pattern> </servlet-mapping> </web-app>
위에서 생성한 HTML 폼을 사용하여 파일을 업로드하려면 다음 URL을 브라우저에서 방문하세요: http://localhost:8080/TomcatTest/upload.jsp, 다음과 같이 표시됩니다: