Java & Kotlin/JSP & Servlet
[JSP] 파일 업로드
전봉근
2019. 12. 21. 21:45
반응형
[JSP] 파일 업로드
1. 파일 업로드 라이브러리 설치
- 웹에서 파일업로드를 하기 위한 라이브러리를 설치
http://www.servlets.com 접속 후 좌측의 com.oreilly.servlet 클릭
-> 스크롤을 아래로 내리면 cos-26Dec2008.zip 가 있다 이것을 다운받는다.
- 다운로드 받은 라이브러리(cos.jar) 복사 -> 경로는 WEB-INF > lib
2. 파일 업로드 프로그래밍
- WebContent > fileFolder라고 업로드한 파일이 저장될 폴더를 만든다.
- 파일첨부 폼 jsp 파일
....
<form action="fileFormOk.jsp" method="post" enctype="multipart/form-data">
파일 : <input type="file" name="file"><br />
<input type="submit" value="File Upload">
</form>
....
- 파일전송폼 jsp 파일
[fileFormOk.jsp]
....
<%
String path = request.getRealPath("fileFolder");
int size = 1024 * 1024 * 10; // 10M
String file = ""; // 기존파일에 중복되면 덮어쓰는것을 방지하기위해 변경할 파일의 이름
String oriFile = ""; // 실제 파일의 이름
try {
// DefaultFileRenamePolicy 은 동일한 파일이 있을경우에 파일뒤에 1,2,3...이 붙으면서 작업이되어진다.
MultipartRequest multi = new MultipartRequest(request, path, size, "EUC-KR", new DefaultFileRenamePolicy());
Enumeration files = multi.getFileNames(); // 파일여러개있을때 파일 네임들을 가져온다
String str = (String)files.nextElement(); // 파일이름을 str에 저장
file = nulti.getFilesystemName(str); // 중복되었을때 그 파일의 이름
oriFile = multi.getOriginalFileName(str); // 실제파일이름
} catch (Exception e) {
e.printStackTrace();
}
%>
- 저장되는 폴더경로
(1) 직접 생성한 폴더 경로
- ../WebContent/fileFolder // 이것은 이클립스 상의 경로이다.
(2) 실제 업로드 파일 경로
- ../tomcat/webapps/{프로젝트명}/fileFolder // 실제 업로드되는 서버(톰캣)의 경로
참고: https://www.inflearn.com/course/%EC%8B%A4%EC%A0%84-jsp-%EA%B0%95%EC%A2%8C/dashboard
반응형