upload_down.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<%@ page language="java" contentType="text/html;charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%--WebContent 폴더 아래 "upload" 폴더 생성 후 실행 --%>
<%--일반 파라미터를 전송할 때 사용하는 인코딩과 파일과 업로드할 대 사용하는 인코딩은 다르다.
스트림 기반의 전송방식은 POST방식은 다음의 두 가지 인코딩 방식에 다라서 전송하는 데이터 형식이 달라진다.
1. application/x-www-form-urlencoded
2. multipart/form-data
지금까지의 예제들은 1번 인코딩을 사용해서 데이터를 전송해왔다.
파일을 업로드하기 위해서는 2번 인코딩을 사용해야 한다.
form 태그의 enctype 속성 값을 "multipart/form-data"로 지정해주면 된다.
method는 post 방식이다.
--%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>fileupload</title>
<style>
table{margin:auto;border:1px;}
tr{background:beige; text-align:center;}
body > form > table > tbody > tr:nth-child(2) > td:nth-child(2) > input[type=text],body > form > table > tbody > tr:nth-child(3) > td:nth-child(2) > input[type=text]{width:70%;}
</style>
</head>
<body>
<%--파일을 업로드하기 위해서 enctype 속성을 "multiport/form-data"로 설정한다.--%>
enctype="multipart/form-data">
<table>
<tr class="yellow">
<td colspan="2" class="center pad"><h3>파일 업로드 폼</h3></td>
</tr>
<tr>
<td>올린 사람</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>제목</td>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<td>파일명1</td>
<td><input type="file" name="fileName1"> <!-- 파일을 선택하여 전송할 수 있도록 type속성을 file로 설정 --></td>
</tr>
<tr>
<td>파일명2</td>
<td><input type = "file" name = "fileName2"></td>
</tr>
<tr>
<td colspan = "2" class = "center green"><input type = "submit" value = "전송"/></td>
</tr>
</table>
</form>
</body>
</html>
Colored by Color Scripter
|
fileUpload2.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html;charset=EUC-KR"
pageEncoding="EUC-KR"%>
<script
<%--request
enctype post 첫번째
두번재 넘겨준 페이지에서 값을 가져오려면 multipartRequest 사용 lib 무조건
WebContent 아래 upload 폴더 생성 필수
--%>
<%--업로드하기 위해 MultipartRequest 객체를 import --%>
<%@page language="java" contentType="text/html;charset=EUC-KR"%>
<%--파일 일므 중복 처리를 하기 위해 DefaultFileRenamePolicy 객체를 import --%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%
/*
application.getRealPath(path);
웹 어플리케이션 path에 대한 로컬 상의 실제 경로를 얻어온다.
*/
String uploadPath = application.getRealPath("upload");
out.println(uploadPath);
int size = 10 * 1024 * 1024;
//퍄일 최대 크기를 10MB로 지정
String name = "";
String subject = "";
String filename1 = "";
String filename2 = "";
String origfilename1 = "";
String origfilename2 = "";
try {
/*업로드 담당하는 부분
- 첫 번째 인자 request : 폼에서 가져온 값을 얻기 위해 request 객체를 전달해 준다.
- 두 번째 인자 uploadPath : 업로드될 파일의 위치다.
- 세 번째 인자 size : 업로드 할 크기이며 지정 크기보다 크면 Exception이 발생한다.
- 네 번째 인자 "euc-kr" : 파일 이름이 한글인 경우 처리하는 부분이다.
- 다섯 번째 인자 : 똑같은 파일을 업로드 할 경우 중복되지 않도록 자동으로 파일이름을 변환해주는 기능을 한다.
*/
MultipartRequest multi = new MultipartRequest(request, uploadPath, size, "euc-kr",
new DefaultFileRenamePolicy());
name = multi.getParameter("name");
subject = multi.getParameter("subject");
//업로드 된 파일의 시스템 상에 업로드 된 실제 파일명을 얻어온다.
filename1 = multi.getFilesystemName("fileName1");
out.println("<br>multi.getFilesystemName(fileName1)=" + filename1);
origfilename1 = multi.getOriginalFileName("fileName1");
out.println("<br>multi.getOriginalFileName(fileName1)=" + origfilename1);
filename2 = multi.getFilesystemName("fileName2");
out.println("<br>multi.getFilesystemName(fileName2)=" + filename2);
origfilename2 = multi.getOriginalFileName("fileName2");
out.println("<br>multi.getOriginalFileName(fileName2)=" + origfilename2);
} catch (Exception e) {
e.printStackTrace();
out.print("오류");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>djqfhem2</title>
</head>
<body>
<input type="hidden" name="name" value="<%=name%>">
<input type="hidden" name="subject" value="<%=subject%>">
<input type="hidden" name="filename1" value="<%=filename1%>">
<input type="hidden" name="filename2" value="<%=filename2%>">
<input type="hidden" name="origfilename1" value="<%=origfilename1%>">
<input type="hidden" name="origfilename2" value="<%=origfilename2%>">
<input type="submit" value="업로드 확인 및 다운로드 페이지 이동">
</form>
</body>
</html>
Colored by Color Scripter
|
fileCkeck.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
request.setCharacterEncoding("EUC-KR");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>업로드한 파일</title>
<style>
table {
margin: auto;
}
tr {
background: beige;
}
tr:eq(2) {
text-align: center;
}
</style>
</head>
<body>
<form>
<table border="1">
<tr>
<td colspan="2">파일 다운로드 폼</td>
</tr>
<tr>
<td>올린 사람</td>
</tr>
<tr>
<td>제목</td>
<td>${param.subject}</td>
</tr>
<tr>
<td>파일명1</td>]
<%--공백X --%>
</a></td>
</tr>
<tr>
<td>파일명2</td>
</a></td>
</tr>
</table>
</form>
</body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5; text-decoration:none">Colored by Color Scripter
|
file_down.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
<%--Servlet context 이용 --%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%--html에서 jsp 페이지의 공백 없애는 JSP 코드 --%>
<%@ page trimDirectiveWhitespaces = "true" %>
<%
String fileName = request.getParameter("file_name");
System.out.println("filename = " + fileName);
String savePath = "upload";
//서블릿 실행 환경 저보를 담고 있는 객체를 리턴한다.
/*(application) 내장 객체르 리턴한다.*/
ServletContext context = pageContext.getServletContext() ;
String sDownloadPath = context.getRealPath(savePath);
//위 두 문장을 한 문장으로 나타내면 다음과 같다
//String sDownloadPath = application.getRealPath (savePath);
/*
String sFilePath = sDownloadPath + "\\" +fileName;
"\" 추가하기 위해 "\\" 사용한다.
Context-Type:전송되는 Content가
*/
String sFilePath = sDownloadPath + "/" +fileName;
System.out.println(sFilePath);
byte b[] = new byte[4096];
//sFilePath에 있는 파일의 MimeType을 구해준다
String sMimeType = context.getMimeType(sFilePath);
System.out.println("sMimeType>>>>>>" + sMimeType );
/*Context-Type : 전송된느 Content가 어떤 유형인지 알려주는 목적을 가ㅣㅈ고 있다.
text/html, image/png, application/octet-stream등의 값을 가진다.
Content-Type을 통해서 브라우저는 해당 데이터를 어떻게 처리해야 할지 판단할 수 있게 된다.
예) image/png : 브라우저는 해당 컨텐트를 이미지로써 간주하게 된다.
- application/octet-stream : 미확인 Binary 정보를 의미하며, 이 경우 브라우저는 파일을 다운로드하는 형태로 동작한다.
- text/javascript: 브라우저는 Content를 jacascript문서로 취급하게 된다.
- octet-stream은 8비트로 도니 일련의 데이터를 뜻한다.
- 지정되지 않은 파일 형식을 의미한다.
*/
if(sMimeType == null){
sMimeType = "application/octet-stream";
}
response.setContentType(sMimeType);
/*
- 이 부분이 한글 파일명이 깨지는 것을 방지해 준다.
- getBytes(캐릭터셋) : 자바 내부에 관리되는 유니코드 문자열을 인자로 지정된 캐릭터셋의 바이트 배열로 반환하는 메서드다.
- String (byte[] bytes, Charset charset)
new String(바이트 배열, 캐릭터 셋) 생성자 : 해당 바이트 배열을 주어진 캐릭터 셋으로 스트링을 만드는 생성자
*/
String sEncoding = new String (fileName.getBytes("euc-kr"), "ISO-8859-1");
System.out.println(sEncoding);
/*
- Content-Disposition : Content가 어떻게 처리되어야 하는지 나타낸다.
1) Content-Dispostion :
inline : 브라우저가 Content를 즉시 출력해야 함을 나타낸다.
이미지인 경우 브라우저 내에서 즉시 출력하며, 문서인 경우 텍스트로 출력한다.
2) Content-Disposition :
attachment : 브라우저는 해당 Content를 처리하지 않고, 다운로드하게 된다.
*/
response.setHeader("Content-Disposition", "attachment : filename = " + sEncoding);
/*
response.setHeader("Content-Disposition" , "inline; filename = " + sEncoding);
*/
//ServletOutputStream so = response.getOutputStream();
try(
//웹 브라우저로의 출력 스트림 생성
BufferedOutputStream out2 = new BufferedOutputStream(response.getOutputStream());
//sFilePath로 지정한 파일에 대한 입력 스트림을 생성한다.
BufferedInputStream in = new BufferedInputStream(new FileInputStream(sFilePath));
){//try() 사용시 알아서 close되기 때문에 finally 필요 없음
int numRead;
//read(b,0,b.length) : 바이트 배열 b의 0번 부터 b.length 크기만큼 읽어온다.
while((numRead = in.read(b,0,b.length))!= -1){
////읽은 데이터가
out2.write(b,0,numRead);
}
}catch(Exception e ){
e.printStackTrace();
}
%>
Colored by Color Scripter
|
'IT > JSP' 카테고리의 다른 글
[JSP] MVC 패턴으로 만든 게시판 01 - net.board.action 패키지 (0) | 2019.05.28 |
---|---|
[JSP] 게시판 (0) | 2019.05.28 |
[AJAX] 에이잭스 (0) | 2019.05.21 |
[JSP] core ex 01 (0) | 2019.05.20 |
[JSP] JSTL core lib (0) | 2019.05.20 |