웹페이지에서 파일업로드 기능을 구현하는데 사용하는 라이브러리
다운로드 주소
http://www.servlets.com/cos/
해당 사이트에서 zip파일을 받아 압출파일 내 lib경로에 cos.jar을 프로젝트 lib에 붙여넣기해서 사용한다
1) html, jsp를 사용하여 < form >태그에서 업로드할 < input type="file" > 로 지정
2) form을 처리할 로직 코딩
new 연산자로 MultipartRequest 객체를 새로 생성한다. MultipartRequest 객체의 생성방법은 여러개가 있는데 보통 인자값을 5개 지정하여 생성한다.
3) 인자값
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
글쓴이 : <input type="text" name="name"><br>
제목 : <input type="text" name="title"><br>
파일지정하기 : <input type="file" name="uploadFIle"><br>
<input type="submit" value="전송">
</form>
</body>
</html>
Servlet
@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
//저장경로
String savePath = "upload";
//최대 업로드 파일 크기 5MB로 제한
int uploadFileSizeLimit = 5*1024*1024;
String encType = "utf-8";
ServletContext context = getServletContext();
System.out.println("context : " + context);
String uploadFilePath = context.getRealPath(savePath);
System.out.println("uploadFilePath : " + uploadFilePath);//실제 폴더(디렉토리)
try {
MultipartRequest multi= new MultipartRequest(
request,
uploadFilePath,
uploadFileSizeLimit,
encType,
new DefaultFileRenamePolicy()
);
String fileName = multi.getFilesystemName("uploadFile"); //업로드된 파일의 이름 얻기
if (fileName == null) {
System.out.println("파일이 업로드 되지 않았음");
} else {
out.println("<br>글쓴이 : " + multi.getParameter("name"));
out.println("<br>제목 : " + multi.getParameter("title"));
out.println("<br>파일명 : " + multi.getParameter("fileName"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}