jsp

[jsp] 답글형게시판 - 파일업로드

sian han 2022. 5. 13. 19:04

※ 답글형게시판 - 파일업로드

 

 

  ▶ 폼형태 설정

 

[1] <input type = "file">

        - 파일을 전송하기 위한 파일 선택창을 사용하기 위해 태그 사용

 

[2] 선택된 파일을 업로드하기 위해서는

     form 태그의 method=“post”, enctype=“multipart/form-data” 지정

 

[3] (post 방식일 경우만해당) post방식일 경우 2가지 인코딩

        - (1) application/x-www-form-urlencoded : 디폴트, 파일 이름만 전송됨

        - (2) multipart/form-data : 파일 이름과 함께 파일 데이터가 전송됨

 

post 형태로 전송한 폼에 담겨진 파라미터들은 request 객체를 통해서 이름에 해당하는 값을 얻어낼 수 있으나

enctype=“multipart/form-data” 로 지정한 폼을 전송했을 경우

request 객체로 얻어낸 파라미터의 이름으로 값을 얻어 낼 수 없음

enctype=“multipart/form-data” 로 전송한 폼에 담겨진 파라미터들에 대한 이름과 값을 가져오고

<input type="file">로 지정된 파일을 서버상의 한 폴더에 업로드하기 위해서 특별한 컴포넌트가 필요함

 = > 해당 컴포넌트 : cos.jar 파일의 MultipartRequest 클래스

 

 

MultipartRequest 클래스

 

생성자

  : 폼의 enctype 속성 값을 multipart/form-data 로 지정한 폼으로부터 파라미터를 읽어오기 위해서

    MultipartRequest 클래스의 객체 생성

          => 이 객체를 통해서 폼에서 지정한 파일이 웹 서버상의 지정된 폴더에 업로드됨

 MultipartRequest(javax.servlet.http.HttpServletRequest request, 
java.lang.String saveDirectory, 
int maxPostSize, 
java.lang.String encoding, 
FileRenamePolicy policy)

첫 번째 매개변수 : request 객체

두 번째 매개변수 : 업로드된 파일이 저장될 파일의 경로

세 번째 매개변수 : 업로드할 파일의 최대크기 (1024*5 이므로 5KB)

네 번째 매개변수 : 인코딩 타입을 지정

다섯 번째 매개변수 : 업로드될 파일명이 기존에 업로드 된 파일명과 이름이 같을 경우

                            덮어쓰기 되는 것을 방지 하기 위해 설정하는 부분

 

 

 

▷ MultipartRequest 의 메서드

 

getContentType(String name)

  리턴타입 : String

  업로드된 파일의 콘텐츠 타입을 리턴, 업로드된 파일이 없으면 null을 리턴

 

getFile(String name)

  리턴타입 : File

  서버상에 업로드된 파일의 파일 객체를 리턴, 업로드된 파일이 없다면 null 을 리턴

 

getFileNames()

  리턴타입 : Enumeration

  폼 요소 중 input 태그 속성이 file로 된 파라미터의 이름들을 리턴,

  upload 된 파일이 없으면 비어 있는 Enumeration 을 리턴

 

 

getFilesystemName(String name)

  리턴타입 : String

  type 속성값이 file 로 지정된 input 태그에 의해 서버상에 실제로 업로드된 파일명을 String 객체 타입으로 리턴

  사용자가 선택한 파일이 실제로 서버상의 폴더에 저장되었을 때의 파일명을 리턴

  ( 업로드시 파일명이 변경될 수 있음 ) 

 

 

getOriginalFileName(String name)

  리턴타입 : String

  사용자가 입력 폼에서 직접 지정한 파일명을 리턴 (이때의 파일명은 파일의 중복을 고려한 파일명 변경 전의 이름) 

 

 

filesystem / originalfile 차이

getFilesystemName(String name) : 파일명이 중복되었을 경우 변경 파일명 리턴

getOriginalFileName(String name) : 파일의 중복을 고려한 파일명 변경 의 이름

 

 

getParameter(String name)

  리턴타입 : String

  String으로 주어진 이름에 대한 값을 리턴,

  값 없이 파라미터가 전송되었거나, 해당되는 이름의 파라미터가 전송되지 않았을 경우 null을 리턴

  request 객체에서 사용되는 getParameter() 메서드와 같이 파라미터의 이름을 매개변수로 받아서

  그 파라미터의 이름에 해당하는 값을 리턴하는 메서드

 

 

getParameterNames()

  리턴타입 : Enumeration

  모든 파라미터 이름을 Enumeration 으로 리턴

  입력 폼에 있는 input 태그 중 type 속성 값이 file 이 아닌 모든 파라미터들의 이름을 리턴

 

getParameterValues(String name)

  리턴타입 : String 배열

  모든 파라미터 이름을 Enumeration 으로 리턴

 

 

getContentType(String name)

  리턴타입 : String

  업로드된 파일의 콘텐츠 타입을 리턴

 

 

 예제 1 )

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@page import="java.io.File"%>
<%
//MultipartRequest 객체 생성 성공 => 업로드 완료
//실패 => IOException 발생(파일 용량 초과 등)

//업로드할 폴더의 절대경로 구하기
//String saveDirectory = config.getServletContext().getRealPath("/upload");
//String saveDirectory="D:\\java\\workspace\\mystudy\\upload";
String saveDirectory=application.getRealPath("/upload");
int maxSize=2*1024*1024; //2메가=>업로드 최대용량 2메가로 제한
String encoding="utf-8";
out.print("upload 디렉토리 : " + saveDirectory + "<br>");

//업로드시 동일한 파일명이 있을 경우 나중에 업로드한 파일에 번호를 붙여 구분해줌
DefaultFileRenamePolicy df = new DefaultFileRenamePolicy();
MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxSize, encoding, df);
out.print("업로드 완료!<br>");
String id = request.getParameter("id");
out.print("id : "+ id +"<br>");
id = multi.getParameter("id");
out.print("id : "+ id +"<br>");
String filename = multi.getFilesystemName("fileName");
out.print("업로드 된 파일명(변경후) : "+ filename +"<br>"); 
String filename1 = multi.getOriginalFileName("fileName");
out.print("업로드 된 파일명 원본 : "+ filename1 +"<br>"); 
String contentType = multi.getContentType("fileName");
out.print("contentType : "+ contentType +"<br>"); 
File myFile = multi.getFile("fileName");
out.print("file size : "+ myFile.length() +"<br>"); 
%>



//body
<form name="frm1" method="post" action="upload_ok.jsp" enctype="multipart/form-data" >
아이디 : <input type="text" name="id"><br>
파일 업로드 : <input type="file" name="fileName" size="30"><br>
<input type = "submit" value="등록"><br>
</form>

 

 

 

 

▶ 예제 2 ) uploadTest.jsp

<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<title>파일 업로드 예제</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form name="frm" method="post" enctype="multipart/form-data" action="uploadTest_ok.jsp">
작성자: <input type="text" name="writer"><br>
제 목: <input type="text" name="title"><br>
파일명: <input type="file" name="uploadFile"><br>
<input type="submit" value="파일 업로드"><br>
</form>
</body>
</html>

 

 

예제 2 ) uploadTest_ok.jsp

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<% String realFolder = "";//웹 어플리케이션상의 절대 경로
//파일이 업로드되는 폴더를 지정한다.
String uploadFolder = "pds_upload";
String encType = "utf-8"; //인코딩타입
int maxSize = 5*1024*1024; //최대 업로드될 파일크기 5MB
ServletContext context = getServletContext();
//현재 jsp페이지의 웹 어플리케이션상의 절대 경로를 구한다
// 주어진 가상경로에 대한 실제 경로를 리턴함
    realFolder = context.getRealPath(uploadFolder); 
    out.println("the realpath is : " + realFolder+"<br>");
        try{
			MultipartRequest mr = null; 
            //전송을 담당할 콤포넌트를 생성하고 파일을 전송한다.
            //전송할 파일명을 가지고 있는 객체, 서버상의 절대경로,최대 업로드될 파일크기, 문자코드, 기본 보
            안 적용(파일 업로드시 기존 파일과 동일한 파일이 있을 때 덮어쓰기 방지)
           
           	mr = new MultipartRequest(request,realFolder,maxSize,encType,new DefaultFileRenamePolicy()); 
            //Form의 파라미터 목록을 가져온다
           
            Enumeration params = mr.getParameterNames(); 
            //파라미터를 출력한다
            
            while(params.hasMoreElements()){ 
                String name = (String)params.nextElement(); //전송되는 파라미터이름
                String value = mr.getParameter(name); //전송되는 파라미터값
                out.println(name + " : " + value +"<br>");
}
out.println("-------------------------------------<br>");
//전송한 파일 정보를 가져와 출력한다
            Enumeration files = mr.getFileNames();
            
            //파일 정보가 있다면
            while(files.hasMoreElements()){
            
            //input 태그의 속성이 file인 태그의 name 속성값 :파라미터이름
            String name = (String)files.nextElement();
            
            //서버에 저장된 파일 이름
            String filename = mr.getFilesystemName(name); 
            
            //전송전 원래의 파일 이름
            String original = mr.getOriginalFileName(name); 
            
            //전송된 파일의 내용 타입
            String type = mr.getContentType(name);
            
            //전송된 파일 속성이 file인 태그의 name 속성값을 이용해 파일 객체 생성
            File file = mr.getFile(name); 
            out.println("파라메터 이름 : " + name +"<br>");
            out.println("실제 파일 이름 : " + original +"<br>");
            out.println("저장된 파일 이름 : " + filename +"<br>");
            out.println("파일 타입 : " + type +"<br>");
            
                if(file!=null){
                out.println("크기 : " + file.length());
                out.println("<br>");
			}
	}//while
}catch(IOException ioe){
	System.out.println(ioe);
}catch(Exception ex){
	System.out.println(ex);
} %>

 

 

 

 


 

파일업로드 게시판에 적용해보기 

 

우선 업로드 될 폴더 만들어놓기

▷ 이렇게 사용될꺼임

<div>
			<span class="sp1">첨부파일</span> 
			<span>
				<a href
="downCount.jsp?no=<%=no%>&fileName=<%=vo.getFileName()%>&originalFileName=<%=vo.getOriginalFileName()%>">
					<%=fileInfo %>
				</a>
			</span>
			<span><%=downInfo %></span>
		</div>

 

▷ jsp

String fileInfo="", downInfo="";
	String fileName=vo.getOriginalFileName();
	if(fileName!=null && !fileName.isEmpty()){
		fileInfo=Utility.getFileInfo(fileName, vo.getFileSize());
		downInfo="다운 : " + vo.getDownCount();
	}

 

▷ VO

package com.herbmall.reboard.model;

import java.sql.Timestamp;

public class ReBoardVO {
	private int no;
	private String name;	
	private String pwd;
	private String title;
	private String email;	
	private Timestamp regdate;	
	private int readcount;
	private String content;
	
	//답변형 추가
	private int groupNo;
	private int step; 
	private int sortNo;
	private String delFlag;
	
	//자료실 추가
	private String fileName;
	private long fileSize; 
	private int downCount;
    private String originalFileName; 
	
	public ReBoardVO() {
		super();
	}

	public ReBoardVO(int no, String name, String pwd, String title, String email, Timestamp regdate, int readcount,
			String content, int groupNo, int step, int sortNo, String delFlag) {
		super();
		this.no = no;
		this.name = name;
		this.pwd = pwd;
		this.title = title;
		this.email = email;
		this.regdate = regdate;
		this.readcount = readcount;
		this.content = content;
		this.groupNo = groupNo;
		this.step = step;
		this.sortNo = sortNo;
		this.delFlag = delFlag;
	}
	
	public ReBoardVO(int no, String name, String pwd, String title, String email, Timestamp regdate, int readcount,
			String content, int groupNo, int step, int sortNo, String delFlag, String fileName, long fileSize,
			int downCount, String originalFileName) {
		super();
		this.no = no;
		this.name = name;
		this.pwd = pwd;
		this.title = title;
		this.email = email;
		this.regdate = regdate;
		this.readcount = readcount;
		this.content = content;
		this.groupNo = groupNo;
		this.step = step;
		this.sortNo = sortNo;
		this.delFlag = delFlag;
		this.fileName = fileName;
		this.fileSize = fileSize;
		this.downCount = downCount;
		this.originalFileName = originalFileName;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Timestamp getRegdate() {
		return regdate;
	}

	public void setRegdate(Timestamp regdate) {
		this.regdate = regdate;
	}

	public int getReadcount() {
		return readcount;
	}

	public void setReadcount(int readcount) {
		this.readcount = readcount;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
	public int getGroupNo() {
		return groupNo;
	}

	public void setGroupNo(int groupNo) {
		this.groupNo = groupNo;
	}

	public int getStep() {
		return step;
	}

	public void setStep(int step) {
		this.step = step;
	}

	public int getSortNo() {
		return sortNo;
	}

	public void setSortNo(int sortNo) {
		this.sortNo = sortNo;
	}

	public String getDelFlag() {
		return delFlag;
	}

	public void setDelFlag(String delFlag) {
		this.delFlag = delFlag;
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public long getFileSize() {
		return fileSize;
	}

	public void setFileSize(long fileSize) {
		this.fileSize = fileSize;
	}

	public int getDownCount() {
		return downCount;
	}

	public void setDownCount(int downCount) {
		this.downCount = downCount;
	}

	public String getOriginalFileName() {
		return originalFileName;
	}

	public void setOriginalFileName(String originalFileName) {
		this.originalFileName = originalFileName;
	}

	@Override
	public String toString() {
		return "ReBoardVO [no=" + no + ", name=" + name + ", pwd=" + pwd + ", title=" + title + ", email=" + email
				+ ", regdate=" + regdate + ", readcount=" + readcount + ", content=" + content + ", groupNo=" + groupNo
				+ ", step=" + step + ", sortNo=" + sortNo + ", delFlag=" + delFlag + ", fileName=" + fileName
				+ ", fileSize=" + fileSize + ", downCount=" + downCount + ", originalFileName=" + originalFileName
				+ "]";
	}
	
	
}

 

 

▷ Utility

public static String displayFile(String filename) {
		String result = "";

		if(filename != null && !filename.isEmpty()) {
			result ="<img src='../images/file.gif'>";
		}

		return result;
	}

	public static String getFileInfo(String filename, long filesize) {
		String result="";
		
		if(filename!=null && !filename.isEmpty()) {
			double fsize=filesize/1024.0;
			
			result+=displayFile(filename)+" ";
			result+=filename;
			result+=" ("+ Math.round(fsize*100)/100.0+"KB)";
		}
		
		return result;
	}