개요
Apache 그룹에서 제공하는 Commons Fileupload 라이브러리를 이용하여 파일 업로드 기능을 구현한다.
Apache Commons – Apache Commons
Welcome to Apache Commons Apache Commons is an Apache project focused on all aspects of reusable Java components. The Apache Commons project is composed of three parts: The Commons Proper - A repository of reusable Java components. The Commons Sandbox - A
commons.apache.org
💡 실행환경
Fileupload: commons-fileupload-1.4.jar
IO: commons-io-2.13.0.jar
💡 실행순서
1. 웹 프로젝트의 WEB-INF/lib 폴더에 jar 등록
2. 파일 업로드 jsp 작성 (반드시 다음과 같이 작성)
<form method="POST" enctype="multipart/form-data">
3. 서블릿작성 UploadServlet.java
- apache에서 제공하는 simplest case, Processing the uploaded items 를 참고하여 작성
FileUpload – Using FileUpload
Using FileUpload FileUpload can be used in a number of different ways, depending upon the requirements of your application. In the simplest case, you will call a single method to parse the servlet request, and then process the list of items as they apply t
commons.apache.org
// 디스크 기반 파일에 대한 factory 생성
DiskFileItemFactory factory = new DiskFileItemFactory();
// 저장소 구성 (임시 위치 사용)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("jakarta.servlet.context.tempdir");
// Or "javax.servlet.context.tempdir"
factory.setRepository(repository);
// 파일 업로드 처리기 생성
ServletFileUpload upload = new JakartaServletDiskFileUpload(factory);
// 요청 구문 분석
List<FileItem> items = upload.parseRequest(request);
- 업로드된 항목 처리
type=text
vstype=file
분리해서 작업처리
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext() ) {
FileItem item = iter.next();
if (item.isFormField()) {
// type="file"이 아닌 것 처리. (주로 type="text")
String name = item.getFieldName(); // tag의 name값
String value = item.getString("utf-8"); // 한글처리
} else {
// type="file"인 것 처리. 한글처리
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
}
}
- 파일 저장
File f = new File("c:\\upload", fileName) ;
try {
item.write(f);
} catch (Exception e) {
e.printStackTrace();
}
실행코드 (UploadServlet.java)
package com.servlet;
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//파일 업로드 기능 구현
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("jakarta.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext() ) {
FileItem item = iter.next();
if (item.isFormField()) {
// type="file"이 아닌 것 처리.
String name = item.getFieldName(); // tag의 name값
String value = item.getString("utf-8"); // 한글처리
System.out.println("text 데이터:" + name +"\t"+value);
} else {
// type="file"인 것 처리.
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
System.out.println("fieldName:" + fieldName);
System.out.println("fileName:" + fileName);
System.out.println("contentType:" + contentType);
System.out.println("isInMemory:" + isInMemory);
System.out.println("sizeInBytes:" + sizeInBytes);
// 진짜 특정 경로에 파일 저장 c://upload
File f = new File("c://upload", fileName) ;
try {
item.write(f);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
'WebServer > JSP&Servlet' 카테고리의 다른 글
[JSP&Servlet] EL (Expression Language) (0) | 2023.08.24 |
---|---|
[JSP&Servlet] JSP 태그 (0) | 2023.08.21 |
[JSP&Servlet] 쿠키를 이용한 간단한 로그인&로그아웃 (0) | 2023.08.21 |
[JSP&Servlet] 세션을 활용한 간단한 로그인&로그아웃 (0) | 2023.08.21 |
[JSP&Servlet] 쿠키 관리 (Cookie) (0) | 2023.08.17 |