-
JSP/Servlet에서의 파일 업로드자바 초보개발/JSP-Servlet 2023. 12. 26. 12:58
cos 라이브러리를 이용하여 파일 업로드를 구현해본다.
Servlets.com | com.oreilly.servlet
www.servlets.com
기존에 <input>태그에 입력한 값을 가져오려면 request.getParameter() 메서드를 사용해서 값을 가져왔는데, <form> 태그의 enctype 속성을
multipart/form-data로 설정하면, 데이터 구조가 바뀌어서 파일 이외에 다른 정보는 가져올 수 없는 경우가 있다고 한다.
이 때, 파일을 업로드하고 같은 <form> 태그 내의 데이터를 가져올 때는 cos 라이브러리의 MultiPartRequest 객체를 사용할 수 있다.
예시 코드- 입력 페이지)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>file upload</title>
</head>
<body>
<h1>파일 업로드</h1>
<form action="fileUploadPro.jsp" method="post" enctype="multipart/form-data">
파일 첨부 : <input type="file" name="uploadFile"> <button>전송</button>
<br>
제목: <input name ="title"><br>
파일 첨부 : <input type = "file" name = "uploadFile">
파일 첨부 : <input type = "file" name = "uploadFile">
파일 첨부 : <input type = "file" name = "uploadFile">
</form>
</body>
</html>

파일 업로드와 데이터 입력 페이지 예시코드 - 입력한 데이터 출력 페이지)
<%
// 서버 기준의 위치
String path = "/upload";
// 파일 시스템 기준의 위치
String realPath = request.getServletContext().getRealPath(path);
System.out.println("실제적인 저장 위치 : " + realPath);
// 자바 부분입니다.
MultipartRequest multi = new MultipartRequest(request, realPath, 1024*1024*1024, "utf-8",
new DefaultFileRenamePolicy());
String fileName = multi.getFilesystemName("uploadFile");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
파일이 올라갔습니다.<br>
<%= realPath %> <br>
request에서 제목 가져오기 : <%= request.getParameter("title") %> <br>
multipart에서 제목 가져오기 : <%= multi.getParameter("title") %> <br>
저장된 파일명 : <%= path + fileName %>
</body>
</html>

request와 MultiPartRequest로 같은 양식태그 안에 타이틀 출력 결과
cos 라이브러리를 통해 <input>태그 name 속성이 똑같을시 처리하는 코드가 구현되어있지만, 파일을 여러개 업로드 할 양식을 만들 때 name속성을 똑같이 만드는 것은 권장되지 않고, 인터넷을 검색해보면 나오는 대부분의 JSP와 cos라이브러리를 사용한 방법은 모두 name속성을 따로 구분해두었다.
그러므로 앞으로 cos라이브러리를 쓰면서 name속성을 항상 구분하려 한다.
Spring을 사용할 때는 더 편하게 할 수 있다고 하는데, 나중에 Spring을 다뤄볼 때 어떻게 다른지 한번 봐야겠다.
'자바 초보개발 > JSP-Servlet' 카테고리의 다른 글
다른 jsp파일을 현재 jsp파일 페이지에 불러오기 - include (0) 2024.01.17 [오류] For input String : "null" 와 Missing end tag for "c : out" (0) 2024.01.08 Servlet을 통한 MVC 모델 구현 개인정리 (1) 2024.01.04 쿠키와 세션 (0) 2023.12.22 JSP/Servlet 이클립스 기본설정,정보 (0) 2023.12.13