파일 업로드

조수경·2022년 1월 11일
0

JSP

목록 보기
21/45

파일 업로드란?

  • 웹 브라우저에서 서버로 파일을 전송하여 서버에 저장하는 것(복사하는것)
  • 이미지 파일, binary 파일, 문서, 텍스트 파일
  • 폼 태그 내에 사용되어야 함. 오픈 라이브러리(common-fileupload)를 사용.
  • 서버로 파일이 업로드되면? 서버는 요청 파라미터를 분석하여 파일을 찾고
    파일 저장 폴더에 저장한다. 이 처리는 단순한 자바 코드로 작성 불가.

fileupload01.jsp

<form name="frm" method="post" action="fileupload01_process.jsp"
     enctype="multipart/form-data">
 <p>파일 : <input type="file" name="filename" /></p>
 <p><input type="submit" value="파일 올리기"></p> 
</form>

파일 올리기 버튼을 누르면

fileupload01_process.jsp

<%@page import="java.io.File"%>
<%@page import="java.util.Iterator"%>
<%@ page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="org.apache.commons.fileupload.*"%>
<!DOCTYPE html>
<html>
<head>

<title>File Upload</title>
</head>
<body>
<%
    //파일이 저장되는 경로
    String path = "C:\\upload";

	DiskFileUpload upload = new DiskFileUpload();
	//업로드할 파일의 최대 크기(1M)
	upload.setSizeMax(1000000);
	//메모리상에 저장할 최대 크기
	upload.setSizeThreshold(4096);
	//업로드된 파일을 임시 저장
	upload.setRepositoryPath(path);
	//요청을 파일로 할 때 리퀘 객체에 담기고 그것을 끄집어 낼려면 파싱 해줘야함
	//파싱: 구문분석(오류잡기) + 의미분석(수행)
	//items 안에는 파일객체 + 폼 데이터가 섞여있음
	List items = upload.parseRequest(request);
	
	Iterator params = items.iterator();
	//폼 페이지에서 전송된 요청 파라미터가 없을 때까지 반복
	while(params.hasNext()){
		//전송된 요청 파라미터의 이름을 가져오도록 Iterator 객체 타입의
		//next() 메소드 사용
		FileItem item = (FileItem)params.next();
		
		if(item.isFormField()){ //요청 파라미터가 일반 데이터(text, checkbox, radio..)
			//?id=a001
			String name = item.getFieldName(); //id
			String value = item.getString("UTF-8"); //a001
			out.print(name + "=" + value+"<br />");
		}else{//폼 페이지에서 전송된 요청 파라미터가 파일(input type='file')
			//요청 파라미터의 이름: 파일내임
			String fileFieldName = item.getFieldName();
			//저장 파일 이름 : 4살.png
			String fileName = item.getName();
			//파일 콘텐츠 유형
			String contentType = item.getContentType();
			
			out.print(fileFieldName + "=" + fileName +"("+
			          contentType + ")");
			//C:Users\SEM-PC\Download\4살.png에서
			//4살.png가 됨
			fileName.substring(fileName.lastIndexOf("\\")+1);
			//파일 크기
			long fileSize = item.getSize();
			//java.io.File -> 파일객체 생성
			File file = new File(path + "/" + fileName);
			//여기서 실제로 파일 생성(복사 완료)
			item.write(file);
			
		}
		
	}
	
%>
</body>
</html>

profile
신입 개발자 입니다!!!

0개의 댓글