초보 개발자의 기록

이미지 업로드- commons(Apache) 본문

JAVA/JSP

이미지 업로드- commons(Apache)

bambinodeveloper 2020. 12. 8. 01:42
728x90

apache의 공식 업로드 컴포넌트 사용

apache commons 하위에는 여러 프로젝트가 구성되어있다(의존관계에있음:dependency)

commons.jar 

mvnrepository.com/search?q=fileupload

 

send.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<style type="text/css">
*{margin-bottom:10px;}
</style>
<script type="text/javascript">
function send(){
	//서버에 제목 및 파일을 전송하자!
	//서버에 전송한다는 것은, 클라이언트로서, 요청한다는 뜻이고 
	//흔히 쓰는 요청방법은 2가지가 잇따..(물론 여러종류가 더 있음)
	//업로드시 Post, Get 중 어떤 방법을 써야하는가?
	//데이터량이 많기 때문에 post 로 전송해야 한다. 
	//post로 전송하려면 입력양식의 범위를 설정하는 태그인 .form태그
	//가 필요하다 
	form1.action="/gallery2/upload.jsp";
	form1.method="post"; //바이너리 파일을 포함될 경우 반드시  post로 ...
	form1.submit();//전송(요청)
}	
</script>
</head>
<body>
	<form name="form1" enctype="multipart/form-data">
		<input type="text" name="msg" placeholder="파일의 제목을 입력하세요"><br>
		<input type="text" name="author" placeholder="작성자명을 입력하세요"><br>
		<input type="file" name="photo"><br>
		<button onClick="send()">업로드</button>
	</form>
</body>
</html>

parseRequest : request 객체의 정보를 꺼내 list collection framework으로 반환해줌

 

FileManager.java

package common;

public class FileManager {
	
	//확장자만 추출하기 
	public static String getExtend(String path) {
		int lastIndex = path.lastIndexOf(".");
		String ext = path.substring(lastIndex+1, path.length());
		//System.out.println(ext);		
		return ext;
	}	
}

 

upload.jsp

<%@page import="common.FileManager"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.List"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.DefaultFileItemFactory"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%
	/*
	파일 업로드 컴포넌트의 종류엔 여러가지가 있지만, 그 중 아파치의 공식 업로드 컴포넌트를 사용해본다
	*/
	
	String saveDir="D:/workspace/javaee_workspace/BoardApp/WebContent/data";
	int maxSize=2*1024*1024; //2M byte제한
	//업로드 객체를 생성해주는 팩토리 객체 : 주로 설정을 담당(서버의 저장경로, 파일의용량제한..)
	DefaultFileItemFactory itemFactory=new DefaultFileItemFactory();
	itemFactory.setRepository(new File(saveDir));//저장될 위치!!!, 물리적인 저장이 아닌, 임시디렉토리
	itemFactory.setSizeThreshold(maxSize); //용량을 지정한 크기로 제한
	
	//이 객체가 실제 업로드를 수행함
	ServletFileUpload upload = new ServletFileUpload(itemFactory);//설정정보를 생성자의 인수로 전달!!!
	
	//FileItem 은 클라이언트의 전송 정보 하나 하나를 의미한다. 즉 html에서의 input 텍스트박스, file 컴포넌트 들..
	//우리의 경우 input type="text" 가 FileItem에 담기고 
	//우리의 경우 input type="file" 가 FileItem에 담기고
	request.setCharacterEncoding("utf-8");
	List<FileItem> items=upload.parseRequest(request);//업로드 컴포넌트에게 클라이언트의 요청 정보를 전달한다!!!
	
	for(FileItem item : items){
		//반복문으로 처리되다보니, 파일만 따로 처리를 하려면, 구분로직이 필요함..
		out.print(item.getFieldName()+"은 텍스트 박스 여부 "+item.isFormField()+"<br>");
		
		if(!item.isFormField()){ //텍스트박스가 아닌것만 업로드 처리!! FormField는 text박스만 의미함
			//업로드 처리하자!! 메모리상의 이미지 정보를 실제 물리적 파일로 저장하자!!
			//새롭게  생성할 파일명
			out.print("당신이 업로드한 파일의 원래 이름은 "+item.getName());
			
			String ext = FileManager.getExtend(item.getName());//확장자 구하기
			String filename = System.currentTimeMillis()+"."+ext;
		
			File file =new File(saveDir+"/"+filename);//비어있는 파일
			item.write(file); //저장 정보를 File 클래스의 인스턴스로 전달!!
			out.print("보고서 작성<br>");
			
			
			out.print("원래 파일명: "+item.getName()+"<br>");
			out.print("생성된 파일명: "+filename+"<br>");
			out.print("저장된 위치: "+saveDir+"<br>");
			out.print("업로드 파일크기: "+item.getSize()+" bytes  <br>");
		}
	}
%>

 

jenkwon92/JavaEE_Workspace

Korea it academy JavaEE class. Contribute to jenkwon92/JavaEE_Workspace development by creating an account on GitHub.

github.com

 

 

728x90
반응형

'JAVA > JSP' 카테고리의 다른 글

Tomcat 이용환경변경  (0) 2020.12.11
이미지 보드  (0) 2020.12.08
이미지 업로드-cos.jar(Oreilly)  (0) 2020.12.07
객체  (0) 2020.12.06
게시판만들기(EditPlus)  (0) 2020.12.06