반응형
파일 업로드(file upload)
: 웹 브라우저에서 서버로 파일을 전송하여 서버에 저장하는 것
텍스트 파일, 바이너리 파일, 이미지 파일, 문서 등 여러가지 파일을 업로드 할 수 있음.
JSP의 폼 태그를 사용하며 파일을 서버에 저장하기 위해 오픈 라이브러리를 이용함.
- JSP 페이지 폼태그 작성 규칙
<form action="JSP 파일" method="post" enctype="multipart/form-data">
<input type="file" name="요청 파라미터 이름" multiple>
</form>
1. form 태그
2. method 속성은 post
3. enctype 속성은 multipart/form-data
4. action 속성은 JSP 파일
5. input 태그의 type 속성은 file
+ 라이브러리 파일
Commons-FileUpload
: 파일 업로드 패키지
서버의 메모리상에서 파일 처리가 가능하도록 지원함.
commons-fileupload.jar, commons-io.jar 파일을 배포 사이트에서 다운로드해서 사용.
- DiskFileUpload 클래스의 메소드
메소드 | 유형 | 설명 |
setRepositoryPath(String repositoryPath) | void | 파일을 입시 저장할 디렉터리 설정 |
setSizeMax(long sizeMax) | void | 최대 파일 크기 설정 |
setSizeThreshold(int sizeThreshold) | void | 메모리상 저장할 최대 크기 설정 |
parseRequest(HttpServletRequest req) | void | multipart/form-data 유형의 요청 파라미터 가져옴 |
- 파일 업로드
fileupload04.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<!-- 파일 업로드 시 체킹!
1) form태그
2) method="post"
3) enctype="multipart/form-data"
4) action="업로드를처리할 jsp의 url주소"
5) <input type="file".. (multiple) />
-->
<!--
요청URI : fileupload04_process.jsp
요청파라미터 : {filename=파일객체}
요청방식 : post
-->
<form action="fileupload04_process.jsp" method="post" enctype="multipart/form-data">
<p>파일 : <input type="file" name="filename" /> </p>
<p><input type="submit" value="파일올리기" /></p>
</form>
</body>
</html>
fileupload04_process.jsp
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="java.util.List"%>
<!--
요청URI : fileupload04_process.jsp
요청파라미터 : {filename=파일객체}
요청방식 : post
-->
<%
// 업로드할 윈도우 경로 : 역슬러시 두 개
String path = "C:\\upload"; // 위치에 폴더를 미리 생성해놔야 함
// commons-fileupload.jar 안에 해당 클래스가 있음
DiskFileUpload upload = new DiskFileUpload();
// 업로드할 파일의 최대 크기
upload.setSizeMax(5000000); // 5Mbyte
// 메모리에 저장할 최대 크기
upload.setSizeThreshold(5 * 4095); // 5 * 1024 * 1024 : 5Mbyte
// 업로드된 파일을 입시로 저장할 경로
upload.setRepositoryPath(path);
// 요청파라미터 : {filename=파일객체}
// parse : 구문분석 / 의미분석
List items = upload.parseRequest(request);
// 요청 파라미터를 Iterator(열거형) 클래스로 변환
Iterator params = items.iterator();
// 요청 파라미터가 없어질때까지 반복(1회 반복 예정)
while(params.hasNext()) {
// FileItem : 1) 일반 폼데이터 2) 파일
FileItem item = (FileItem)params.next();
if(item.isFormField()) { // 1) 일반(input type="text", radio, checkbox, textarea, select)
} else { // 파일(input type="file" name="filename")(o)
// 요청파라미터 : {filename=파일객체} => item
String fileFieldName = item.getFieldName(); // filename
String fileName = item.getName(); // 업로드된 파일의 이름 (ex : chi12.png)
String contentType = item.getContentType(); // 만약 이미지파일이라면 MIME TYPE : image/png
long fileSize = item.getSize(); // 파일 크기
//fileName => C:\\Users\\PC10\\Pictures\\chi12.png
//파일명만 추출(경로는 제외)
//마지막 \\의 위치를 찾아서 +1을 하면 1이 나오는데 거기서부터 끝까지 추출 => chi12.png
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
// 계획. c:\\upload\\chi12.png
File file = new File(path + "\\" + fileName);
// 복사 실행
// 파일객체.write(계획)
item.write(file);
out.print("===============================<br />");
out.print("요청 파라미터 이름 : " + fileFieldName + "<br />");
out.print("저장 파일 이름 : " + fileName + "<br />");
out.print("파일 콘텐츠 유형 : " + contentType + "<br />");
out.print("파일 크기 : " + fileSize + "<br />");
}
}
%>
- 파일 중복 방지 업로드
fileupload05.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
// 이미지 미리보기 시작
// <input type="file" id="filename" name="filename" />
// $("input[name='filename']")
$("#filename").on("change", handleImg);
function handleImg(e){
//e.target : <input type="file" id="uploadFile" name="filename" />
let files = e.target.files; // 파일들
// fileArr = [a.jpg, b.jpg, c.jpg]
let fileArr = Array.prototype.slice.call(files);
$("#pImg").html("");
// f : 파일오브젝트 1개
fileArr.forEach(function(f){
// 이미지 체킹
if(!f.type.match("image.*")) {
alert("이미지 확장자만 가능합니다.");
return; // 함수 종료
}
// 이미지가 맞으면
let reader = new FileReader();
// e : reader가 이미지 객체를 읽는 이벤트
reader.onload = function(e) {
let img_html = "<img src='" + e.target.result + "' style='width:10%;' />";
$("#pImg").append(img_html);
}
reader.readAsDataURL(f);
});
}
});
</script>
<title>File Upload</title>
</head>
<body>
<!-- 파일 업로드 시 체킹!
1) form태그
2) method="post"
3) enctype="multipart/form-data"
4) action="업로드를처리할 jsp의 url주소"
5) <input type="file".. (multiple) />
-->
<!--
요청URI : fileupload05_process.jsp
요청파라미터 : {name=개똥이, subject=개똥이의 모험, filename=파일객체}
요청방식 : post
-->
<form id="fileForm" name="fileForm" action="fileupload05_process.jsp" method="post"
enctype="multipart/form-data">
<!-- FileItem, isFormField() : true -->
<p>이름 : <input type="text" name="name" /></p>
<p>제목 : <input type="text" name="subject" /></p>
<p id="pImg"></p>
<!-- FileItem, isFormField() : false -->
<p>파일 : <input type="file" id="filename" name="filename" multiple/></p>
<p><input type="submit" value="파일올리기" /></p>
</form>
</body>
</html>
fileupload05_process.jsp
<%@page import="java.io.File"%>
<%@page import="java.util.UUID"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<!--
요청URI : fileupload05_process.jsp
요청파라미터 : {name=개똥이, subject=개똥이의 모험, filename=파일객체}
요청방식 : post
-->
<%
String path = "c:\\upload";
DiskFileUpload upload = new DiskFileUpload();
upload.setSizeMax(5000000); // 5M
upload.setSizeThreshold(5*4096);
upload.setRepositoryPath(path); // 임시저장경로
List items = upload.parseRequest(request);
Iterator params = items.iterator(); // 요청 파라미터들을 담음
while(params.hasNext()) {
FileItem item = (FileItem)params.next();
if(item.isFormField()) { // 1) name=개똥이, subject=개똥이의 모험
String name = item.getFieldName(); // name, subject
String value = item.getString("UTF-8"); // 개똥이, 개똥이의 모험
out.print(name + "=" + value + "<br />");
} else { // 2) filename=파일객체
String fileFieldName = item.getFieldName(); // filename
String fileName = item.getName(); // c:\\users\\picture\\사진
String contentType = item.getContentType(); // MIME
long fileSize = item.getSize();
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
// 파일 중복 방지 시작
// java.util.UUID => 랜덤값 생성
UUID uuid = UUID.randomUUID();
//sdalfksadjk_111가1236.jpg
fileName = uuid.toString() + "_" + fileName;
// 파일 중복 방지 끝
File file = new File(path + "\\" + fileName);
// 복사 실행
item.write(file);
out.print("===============================<br />");
out.print("요청 파라미터 이름 : " + fileFieldName + "<br />");
out.print("저장 파일 이름 : " + fileName + "<br />");
out.print("파일 콘텐츠 유형 : " + contentType + "<br />");
out.print("파일 크기 : " + fileSize + "<br />");
}
}
%>
반응형
'스프링' 카테고리의 다른 글
[스프링] 14장 정규 표현식 (0) | 2024.04.12 |
---|---|
[스프링] 13장 유효성 검사 (0) | 2024.04.11 |
[스프링] 10.5장 과제 (0) | 2024.04.08 |
[스프링] 10장 쇼핑몰 시스템2 (0) | 2024.04.02 |
[스프링] 8.5장 과제 (0) | 2024.04.01 |