AngelPlayer`s Diary

파일 업로드 - 웹 브라우저에서 서버로 파일을 전송하여 서버에 저장하는 것

 

- 폼 태그를 이용하여 파일을 전송

form 태그의 method 속성은 무조건 POST 방식을 써야 함

form 태그의 enctype 속성은 무조건 multipart/form-data를 써야 함

form 태그의 action 속성은 파일 업로드를 처리할 jsp 파일을 설정해야 함

input 태그의 type 속성은 file로 설정해야 함

<form action="업로드 파일을 처리할 JSP 파일" method="POST" enctype="multipart/form-data">
    <input type="file" name="파라미터 명1">
    <input type="file" name="파라미터 명2">
</form>

 

 

 

- 파일 업로드 처리

자바 코드만 가지고는 파일 업로드 처리를 처리할 수 없기 때문에 오픈 라이브러리를 사용

cos.jar - MultipartRequest를 이용한 방법

...\WebContent\WEB-INF\lib에 cos.jar 파일을 넣음

 

cos.jar.zip
0.05MB

 

www.servlets.com/

 

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

 

commons-fileupload.jar - 아파치 API를 이용

 

commons.zip
0.23MB

 

commons.apache.org/downloads/

 

Apache Commons – Apache Commons

Downloads Binary and source releases and links into the archives may be obtained by selecting a project below Release Announcements We recommend that you subscribe to the Apache Announce mailing list to be notified when releases are made by the Commons pro

commons.apache.org

 

 

 

- MultipartRequest를 이용한 파일 업로드

웹 페이지에서 서버로 업로드되는 파일 자체만을 다루는 클래스

multipart/form-data 유형과 POST 방식의 요청 파라미터 등을 분석하여 일반 데이터와 파일 데이터를 구분하여 접근

한글 인코딩 값 얻기 쉬움

서버 디렉토리에 동일한 파일명이 있으면 파일명을 자동으로 변경해줌

 

<%@ page import="com.oreilly.servlet.*"%>
<%@ page import="com.oreilly.servlet.multipart.*"%>
<%@ page import="java.util.*"%>

// MultipartRequest(request, "경로", 파일 크기, "UTF-8", 동일 명 파일 처리);
MultipartRequest multi = new MultipartRequest(request, "c:\\upload", 5*1024*1024, "UTF-8", new DefaultFileRenamePolicy());

 

 

 

- Commons-FileUpload를 이용한 파일 업로드

<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>

<%
	String fileUploadPath = "c:\\upload";

	DiskFileUpload upload = new DiskFileUpload();
	
	List items = upload.parseRequest(request);
	
	Iterator params = items.iterator();
	
	while (params.hasNext()) {
		FileItem fileItem = (FileItem) params.next();
		if (!fileItem.isFormField()) {
			String fileName = fileItem.getName();
			fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
			File file = new File(fileUploadPath + "/" + fileName);
			fileItem.write(file);
		}
	}
%>

 

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band