파일 업로드 서블릿.
파일 업로드가 안되네 -_-;;
=_=..
일단 소스라도.
package study.fileupload;
import java.io.File;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
private String fileRepository;
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
System.out.println("요청 처리");
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
try {
List /* FileItem */items = upload.parseRequest(req);
for (int i = 0; i < items.size(); ++i) {
FileItem item = (FileItem) items.get(i);
if (item.isFormField()) {
} else {
try {
// 업로드된 파일을 가지고 처리를 한다.
File uploadedFile = new File("D:\\temp"
+ File.separator + item.getName());
System.out.println("저장 경로 : "
+ uploadedFile.getAbsolutePath());
item.write(uploadedFile);
System.out.println("파일 저장 완료 ["
+ uploadedFile.length() + "]");
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
} else {
System.out.println("멀티파트 요청이 아님.");
}
}
public void destroy() {
super.destroy();
}
public void init(ServletConfig config) throws ServletException {
String tmpPath = config.getInitParameter("fileRepositoryPath");
String webRootPath = config.getServletContext().getRealPath("/");
String path = webRootPath + "/WEB-INF/" + tmpPath;
if (path == null) {
throw new IllegalArgumentException("fileRepositoryPath 설정이 없음.");
}
File f = new File(path);
if (f.exists()) {
if (f.isDirectory()) {
if (f.canRead() && f.canWrite()) {
fileRepository = f.getAbsolutePath();
} else {
throw new IllegalArgumentException(path
+ " 읽기 또는 쓰기 권한 없음.");
}
} else {
throw new IllegalArgumentException(
"fileRepositoryPath 값은 디렉토리 경로를 지정해야함. [" + path + "]");
}
} else {
System.out.println("지정된 디렉토리가 없어 생성함. [" + path + "]");
if (f.mkdir()) {
fileRepository = f.getAbsolutePath();
} else {
throw new IllegalArgumentException("설정된 디렉토리 생성실패 [" + path
+ "]");
}
}
System.out.println("파일 저장 경로 [" + fileRepository + "]");
}
}
서블릿 맵핑 설정
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>
study.fileupload.FileUploadServlet
</servlet-class>
<init-param>
<param-name>fileRepositoryPath</param-name>
<param-value>upload</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/Upload</url-pattern>
</servlet-mapping>