📌 https://commons.apache.org/
📂 apache제공 Commons Fileupload 라이브러리 이용하여 파일업로드 하기
1. jar파일 2개 다운받기 (C:\servlet_study 압축풀기)
- FileUpload : commons-fileupload-1.4-bin.zip
- IO : commons-io-2.13.0-bin.zip
2. 빌드패스 (프로젝트>lib>자동빌드패스)
- commons-fileupload-1.4.jar
- commons-io-2.13.0.jar
<form method="post" enctype="multipart/form-data">
4. 서블릿 작성 (UploadServlet.java)
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()) {
String name = item.getFieldName();
String value = item.getString("utf-8");
System.out.println("text 데이터: " + name + "\t" + value);
} else {
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);
File f = new File("c:\\upload", fileName);
try {
item.write(f);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
- import
java.util.List
org.apache.commons.fileupload
java.io.File
📂 파일 다운로드