Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags more
Archives
Today
Total
관리 메뉴

기록

JSP 파일업로드 3 본문

JSP

JSP 파일업로드 3

9400 2023. 1. 4. 13:57
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<!-- commons-fileupload.jar 오픈 라이브러리
     - 서버(톰캣 컨테이너)의 메모리상에서 파일처리가 가능하도록 지원해줌
     - (JSP)DiskFileUpload 객체사용
     - (SPRING)MultipartFile 객체사용 
     - DiskFileUpload upload...
     - upload.setRepositoryPath(경로) : 업로드된파일을 임시로 저장할 디렉터리 설정
     - upload.setSizeMax(long 최대 파일의 크기)
     - upload.setSizeThreshold(int 메모리상의 저장 최대크기)
     - upload.parseRequest(HttpServletReqest 요청 파라미터를 담은 객체(req))
     - parse : 구문분석/의미분석
			ex)김대리 xml 파싱했나요? xml의 구문과 의미를 분석하여 처리했나요?
     -->

	<!-- 폼페이지 -->
	<form action="fileupload04_process.jsp" method="POST" enctype="multipart/form-data">
		<p>이름 : <input type="text" name="name" /></p>
		<p>제목 : <input type="text" name="subject" /></p>
		<p>파일 : <input type="file" name="filename" /></p>
		<p><input type="submit" value="파일올리기"></p>
	</form>
</body>
</html>

처리페이지

<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
 	//파일 저장 path
 	String path = "c:\\upload";
	//commons-fileupload.jar 안에 해당 클래스가 있음
	DiskFileUpload upload = new DiskFileUpload();
	//long 최대 파일의 크기 (1Mbytes)
	upload.setSizeMax(10000000);
	//int 메모리상의 저장 최대 크기 (4Kbytes)
	upload.setSizeThreshold(4096);
	//임시로 저장할 디렉터리 설정
	upload.setRepositoryPath(path);
	//요청파라미터를 받음
	//formFild(name="개똥이"&subject=소설) 2개
	//파일객체(filename이라는 파일 객체) 1개
	//parse : 구문/의미분석
	//items.size() => 3
	List items = upload.parseRequest(request);
	//items 리스트 객체를 Iterator(열거) 클래스로 변환
	Iterator params = items.iterator();
	//요청 파라미터가 없을 때 까지 반복(3회반복)
	while(params.hasNext()){
		//FileItem : 1)일반 데이터(name, subject) 2)파일(filename)
		FileItem item = (FileItem)params.next();
		
		if(item.isFormField()){ //일반데이터이면(name,subject)
			//?name=개똥이&subject=소설
			String name = item.getFieldName(); //파라미터의 name값 가져옴(name,subject)
			String value = item.getString("UTF-8"); //파라미터의 VALUE값 가져옴 (개똥이, 소설)
			
			//name=개똥이
			//subject=소설
			out.print("<p>" + name + "="+value+"</p>");
		}else{ //파일
			String fileFieldName= item.getFieldName(); //파라미터의 name값 가져옴(filename)
			String fileName= item.getName(); //선택된 업로드할 파일명
			String contentType = item.getContentType(); // MINE 타입( 만약 이미지 : images/jpeg)
		
			//파일명만 추출(client쪽의 경로는 제외)
			//c:\\Users\\test\\Pictures\\개똥이.png
			//마지막 \\의 위치를 찾아서 +1을 하면 "개"부터 끝까지 추출 => 개똥이.png
			
			fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
			//파일의 크기
			long fileSize = item.getSize();
			//c:\\upload\개똥이.png로 복사해야함 => 계획
			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 />");
		}
	}
%>

 

출력결과

출력결과

C드라이브 - upload파일에도 파일이 잘 들어가면 성공~! 

'JSP' 카테고리의 다른 글

JSP 상품 등록 후 자동 새로고침 설정  (0) 2023.01.05
JSP 파일업로드 4 (숙제)  (2) 2023.01.04
JSP 파일업로드 2  (0) 2023.01.04
JSP 파일업로드  (0) 2023.01.04
JSP 상품등록 페이지 만들기  (0) 2023.01.03
Comments