파일 업로드(File Upload)
목표: 웹 브라우저를 통해서 파일을 전송
1. 파일 업로드의 기본적인 폼
■ form 태그 구성
✓ <form name="폼이름" method="post" enctype="multipart/form-data">
■ Input 태그 지정
✓ <input type="file" name="파일명">
2. fileSelect.jsp
다음과 같이 user, title 그리고 선택된 file을 넘겨주는 페이지를 작성합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<%@ page contentType="text/html;charset=EUC-KR"%>
<html>
<body>
<form name="frmName" method="post" enctype="multipart/form-data"
action="viewPage.jsp">
user<br/>
<input name="user"><br/>
title<br/>
<input name="title"><br/>
file<br/>
<input type="file" name="uploadFile"><br/><br/>
<input type="submit" value="UPLOAD"><br/>
</form>
</body>
</html>
|
cs |
3. cos.jar 파일
Servlets.com
Home What's New? COS File Upload Library Servlet Polls Mailing Lists Servlet Engines Servlet ISPs Servlet Tools Documentation Online Articles The Soapbox "Java Servlet Programming, Second Edition" "Java Enterprise Best Practices" Speaking & Slides About Ja
www.servlets.com
COS File Upload Library. 클릭
com.oreilly.servlet 클릭
cos-20.08.zip 다운로드
그다음 cos.jar 파일을 이클립스 해당 프로젝트 lib 폴더에 복사해줍니다.
4. viewPage.jsp
fileSelect.jsp에서 넘겨준 값들을 확인하기 위해 viewPage.jsp를 작성합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<%@page contentType="text/html; charset=EUC-KR" %>
<%@page import="com.oreilly.servlet.MultipartRequest" %>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="java.util.*,java.io.*"%>
<%
//String saveFolder = "파일경로";
String saveFolder = application.getRealPath("/filestorage") ;
String encType = "EUC-KR";
int maxSize = 5 * 1024 * 1024;
try {
MultipartRequest multi = null;
multi = new MultipartRequest(request, saveFolder, maxSize,
encType, new DefaultFileRenamePolicy());
String user = multi.getParameter("user");
String title = multi.getParameter("title");
out.println("user: " + user + "<br/>");
out.println("title: " + title + "<br/>");
out.println("<hr>");
String fileName = multi.getFilesystemName("uploadFile");
String original = multi.getOriginalFileName("uploadFile");
String type = multi.getContentType("uploadFile");
File f = multi.getFile("uploadFile");
out.println("저장된 파일 이름 : " + fileName + "<br/>");
out.println("실제 파일 이름 : " + original + "<br/>");
out.println("파일 타입 : " + type + "<br/>");
if (f != null) {
out.println("크기 : " + f.length()+"바이트");
out.println("<br/>");
}
} catch (IOException ioe) {
System.out.println(ioe);
} catch (Exception ex) {
System.out.println(ex);
}
%>
|
cs |
5. 실행 결과
'Language > └JSP | Servlet' 카테고리의 다른 글
[JSP] 이클립스에서 JDBC로 MySQL 연동하기 | Yoon's Dev (0) | 2021.05.12 |
---|---|
[Servlet] Servelt 서블릿 기초 문법, 클래스, 메서드, 라이프 사이클 | Yoon's Dev (0) | 2021.04.28 |
[JSP] JSP 기초문법 선언문(Declaration), 스크립트릿(Scriptlet), 표현식(Expression) | Yoon's Dev (0) | 2021.04.22 |
[JSP] getParameter(), getParameterValues()를 이용한 학생 정보 입력 값 전달 | Yoon's Dev (0) | 2021.04.15 |
[JSP] getParameter()를 이용한 간단한 사칙연산 계산기 | Yoon's Dev (0) | 2021.04.14 |