Apache Commons fileUpload 구현 파일 업로드 중 하나

쓸데없는 말은 그만하고 주제를 향해 달려갔다.
두 개의jar 패키지가 필요합니다.
commons-fileupload.jar
Commons IO의jar 패키지(본고는commons-io-2.4.jar 사용)
Servlet을 사용하여 파일 업로드를 수행합니다.

package web.servlet;

import java.io.IOException;
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 java.io.File;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String uploadPath = "D:\\temp"; //  
private String tempPath = "d:\\temp\\buffer\\"; //  
File tempPathFile;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(4096); //  , 4kb
factory.setRepository(tempPathFile);//  
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(4194304); //  , 4MB
List<FileItem> items = upload.parseRequest(request);//  
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.print("upload succeed");
} catch (Exception e) {
//  
e.printStackTrace();
}
}
public void init() throws ServletException {
File uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}
jsp

<%@ page language="java" contentType="text/html; charset=ISO--"
pageEncoding="utf-"%>
<!DOCTYPE html PUBLIC "-//WC//DTD HTML . Transitional//EN" "http://www.w.org/TR/html/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB">
<title>File upload</title>
</head>
<body>
<!-- // action="fileupload" web.xml <servlet-mapping> <url-pattern> . -->
<form name="myform" action="UploadServlet" method="post"
enctype="multipart/form-data">
File:<br>
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html> 
이렇게 하면 하나의 파일 업로드 기능을 간단하게 실현할 수 있다. 물론 이것은 가장 기본적이고 계속 연구 중이다.

좋은 웹페이지 즐겨찾기