본문 바로가기
study/MVC

[MVC] 16. MVC Model1 방식 - 회원가입 (파일업로드)

by 금이패런츠 2022. 4. 11.
728x90
반응형
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%--src/main/webapp/upload/uploadForm.jsp --%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 예제</title>
</head>
<body>
<%--
   enctype="multipart/form-data" : 파일 업로드시 선택된 파일의 내용까지 서버로 전송하도록 설정.
   파일 업로드를 하기위해서는 enctype="multipart/form-data" 속성을 form에 설정해야 함. 반드시 method="post" 여야함.
 
   -- 주의사항 --
   action되는(upload.jsp) 페이지에서는 request 객체에서 파라미터값을 직접 조회 불가.
   : cos.jar 파일에 설정된 MultipartRequest 객체를 사용해야함.
 --%>

<form action="upload.jsp" method="post" enctype="multipart/form-data">
<table>
	<tr>
		<th>올린사람</th>
			<td><input type="text" name="name"></td>
	</tr>
	<tr>
		<th>제목</th>
			<td><input type="text" name="title"></td>
	</tr>
	<tr>
		<th>파일</th>
			<td><input type="file" name="file1"></td>
	</tr>
	<tr>
			<td colspan="2"><input type="submit" value="전송"></td>
	</tr>
</table>
</form>
</body>
</html>

<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.io.File"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%--src/main/webapp/upload/upload.jsp --%>   
<%--
	uploadForm.jsp 에서 action 되는 페이지.
	uploadForm.jsp 페이즈의 enctype="multipart/form-data 이므로 request로 직접 파라미터 조회 불가
	=> cos.jar 파일의 MultipartRequest 클래스를 이용
--%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>파일 업로드 결과</title>
</head>
<body>
<%
	String uploadPath = application.getRealPath("/") + "upload/"; //실제파일이 업로드되는 서버에서 위치
	int size = 10 * 1024 * 1024; //10M. 업로드 가능 파일의 크기 설정
	File f = new File(uploadPath);
	if(!f.exists()) f.mkdirs(); //upload 폴더가 없으면 폴더 생성
	/*
		MultipartRequest() => 객체 생성시 파일 업로드 완성
		request : 클라이언트의 요청정보 저장. 2개의 파라미터, 1개의 파일정보 
		uploadPath : 업로드되는 서버의 폴더 정보 설정
		size : 업로드 가능 최대 파일 크기
		utf-8 : 파라미터 인코딩 설정
	*/
	MultipartRequest multi = new MultipartRequest(request, uploadPath, size, "utf-8");
	String name = multi.getParameter("name"); //name 파라미터의 값
	String title = multi.getParameter("title"); //title 파라미터의 값
	String fname = multi.getFilesystemName("file1"); //file1 파일의 이름. 업로드된 파일 이름
%>
업로드위치:<%=uploadPath %><br>
올린사람:<%=name %><br>
제목:<%=title %><br>
파일:<a href="<%=fname %>"><%=fname %></a><br>
</body>
</html>
728x90
반응형