상세 컨텐츠

본문 제목

파일 업로드 / 다운로드 구현 (1) - 파일 업로드

web/업로드 & 다운로드

by 매일매일 배우는 개발자 2021. 1. 11. 13:12

본문

728x90

파일 업로드를 서버에서 편리하게 구현하기 위해서는 cos.jar 또는 Commons Fileupload.jar 와 Commons io.jar 를 다운받아야 사용할 수 있다.

 

여기서는 Commons Fileupload.jar, Commons io.jar를 사용하여 파일 업로드를 구현해보자 (Commons Fileupload.jar, Commons io.jar 는 Apache 사이트에서 다운받을수 있다)

 

라이브러리를 (Commons Fileupload.jar, Commons io.jar)를 다운받아 프로젝트의 lip폴더 안에 넣으면 준비 완료!!

 

Commons Fileupload.jar : commons.apache.org/proper/commons-fileupload/commons.apache.org/proper/commons-fileupload/

 

Commons io.jar : http://commons.apache.org/proper/commons-io

 

 

 

 

FileUpload – Home

Commons FileUpload The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications. FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That

commons.apache.org

 

 

먼저, 파일 업로드를 하기위해서는 view 페이지 입력폼에 enctype 속성값을 multipart/form-data로 지정해 줘야한다.

(파일,사진 등의 이름과 데이터 값을 얻기위해 multipart/form-data와 method 속성을 post로 지정해야 한다.)

 

1.Index.jsp

 

<form action="upload" method="post" enctype="multipart/form-data">
	이름 : <input type="text" name="name">
	비밀번호 : <input type="password" name="password">
	파일 : <input type="file" name="file">
	<input type="submit" value="업로드"> 
</form>

 

  • enctype 속성의 값을 multipart/form-data로 설정
  • method 속성의 값을 post로 설정
  • input type 을 file로 설정

 

3가지를 해야 반드시 입력값의 데이터들이 함께 controller로 전송된다.

 

2. upload Controller

입력폼에서 전송받은 데이터들을 처리할 페이지

 

Map<String, String> articleMap = new HashedMap<String, String>();
		String encoding = "UTF-8";
		File currentDirPath = new File("C:\\files\\upload");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		/*제약조건 생성*/
		factory.setSizeThreshold(1024*1024*1); //업로드 메모리크기
		factory.setRepository(currentDirPath); //업로드 공간
		ServletFileUpload upload = new ServletFileUpload(factory); //새 파일 업로드 핸들러
		
		try {
			upload.setHeaderEncoding(encoding);
			List<FileItem> items = upload.parseRequest(request); //요청 구문 분석
			Iterator<FileItem> iter = items.iterator();
			while(iter.hasNext()) {
				FileItem item = iter.next();
				if(item.isFormField()) {//파일이 아니라면
					String name = item.getFieldName();
					String value = item.getString(encoding);
				}else {//파일이라면?
					String fieldNameName = item.getFieldName();
					String fileName = item.getName();
					File uploadFile = new File(currentDirPath + "/" + fileName);
					articleMap.put(fieldNameName, fileName);
					item.write(uploadFile);
					
				}
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}		
			
			
		}

 

  • DiskFileItemFactory - 업로드의 데이터를 메모리에 임시로 저장할 크기를 만듬
  • setRepository : 업로드 저장파일을 임시로 저장할 폴더 생성
  • setSizeThreshold - 업로드 메모리 크기를 지정
  • ServletFileUpload - 파일 업로드 핸들러

 

Request에 저장되어 있는 데이터를 ServletFileUpload에 담아 Iterator반복자를 통해 꺼내어 온다.

 

index.jsp 페이지로 가서 업로드를 실행 시켜 업로드 하면 "C:\files\upload" 폴더안에 파일이 업로드 되어있다는걸 알수있다.

 

setRepository 에 폴더를 생성해야 에러가 나지않는다.

 

 

 

 

 

 

 

728x90

관련글 더보기