[JSP] 파일 업로드하기

heubanufi·2024년 4월 3일

JSP/Servlet

목록 보기
3/4

COS 라이브러리를 이용하여 파일을 업로드하고 다운로드하기

파일업로드 : cos.jar (http://www.servlets.com/cos)
0. 사용할 라이브러리 파일 cos.jar 빌드패스 등록
(WebContent > WEB-INF > lib > cos.jar)
1. form 태그 선언 : method="post" 설정(POST 방식만 가능)
2. form 태그 선언 : enctype="multipart/form-data" 설정
3. form input 태그 : <input type="file" ...>

WebContent에 upload 폴더 생성하여 사용

파일을 업로드하는 폼 태그 작성

ex01_fileup_cos.jsp

	<form action="ex01_result_cos.jsp" method="post" enctype="multipart/form-data">
		<p>올린사람: <input type="text" name="name"></p>
		<p>제목: <input type="text" name="title"></p>
		
		<p>파일: <input type="file" name="filename"></p>
		<input type="submit" value="파일업로드">
	</form>

파일 업로드 후 넘어가는 화면

ex01_result_cos.jsp

	<h1>파일업로드 결과보기</h1>
	<h2>올린사람(name): <%=mr.getParameter("name") %></h2>
	<h2>제목(title): <%=mr.getParameter("title") %></h2>
	
	<h2>파일(filename): <%=mr.getParameter("filename")%></h2><%--null --%>
	<h2>원본파일명: <%=mr.getOriginalFileName("filename") %></h2>
	<h2>저장파일명: <%=mr.getFilesystemName("filename") %></h2>
	<h2>파일타입: <%=mr.getContentType("filename") %></h2>
	<hr>
	
	<%
		File file = mr.getFile("filename");
		out.println("<h2> 저장된파일명: " + file.getName() + "</h2>");
		out.println("<h2> 파일사이즈(byte): " + file.length() + "</h2>");
	%>
	
	<hr>
	<h2>파일 다운로드</h2>
	<a href="download.jsp?path=upload&filename=<%=mr.getFilesystemName("filename") %>">다운로드할 파일(<%=mr.getOriginalFileName("filename") %>)</a>
   <%
   	//한글처리
   	request.setCharacterEncoding("UTF-8");
   
    // form 태그에 enctype="multipart/form-data" 설정하면 request 객체를 통한 파라미터 값 조회 안 됨
	String name = request.getParameter("name");
		   
	//파일을 저장할 위치 지정
	//String path = this.getServletContext().getRealPath("/upload");
    String path = application.getRealPath("/upload");
	System.out.println("> path: " + path);
	
	MultipartRequest mr = new MultipartRequest(
			request, //요청객체
			path, //실제 파일을 저장할 경로
			10 * 1024 * 1024, //10MB
			"UTF-8", //인코딩 형식
			new DefaultFileRenamePolicy() //동일 파일명이 있으면 이름 자동 변경 저장
			);
   %>

System.out.println("> path: " + path);
코드를 작성하여 업로드된 파일이 어디에 저장되었는지 콘솔에서 확인

파일 다운로드하기

    <%
    //한글처리
    request.setCharacterEncoding("UTF-8");
    
    //전달받은 파라미터 값 확인(추출)
    String path = request.getParameter("path"); //저장된 폴더명
    String filename = request.getParameter("filename");
    System.out.println(">path: " + path);
    System.out.println(">filename: " + filename);
    
    //실제 파일이 저장된 경로 확인
    String realPath = application.getRealPath(path);
    System.out.println(">> realPath: " + realPath);
    
    //다운로드 받을 수 있도록 클라이언트 응답 문서타입 변경
    response.setContentType("application/x-msdownload");
    
    //클라이언트 헤더정보를 첨부파일이 있는 것으로 변경
    //response.setHeader("Content-Disposition", "attachment;filename=" + filename);
	response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20"));
    
	//------- 실제 파일 읽고 / 쓰기 작업 ----------
	FileInputStream fis = null;
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;
	
	File file = new File(realPath + "/" + filename); 
	
	if(!file.isFile()) {
		System.out.println(":::파일이 아닙니다");
		return;
	}
	//파일복사
	try {
	fis = new FileInputStream(file);
	bis = new BufferedInputStream(fis);
	
	//파일 쓰기 객체 생성
	bos = new BufferedOutputStream(response.getOutputStream());
	
	//파일 읽고, 쓰기
	int readValue = bis.read();
	while(readValue != -1){
		bos.write(readValue);
		readValue = bis.read();
	}
	//JSP 출력스트림과 서블릿 출력스트림이 겹쳐서 발생하는 오류 발생시 해결법
		out.clear(); //출력 버퍼 삭제
		out = pageContext.pushBody(); //현재 출력버퍼를 대체해서 스택에 저장
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		bis.close();
		bos.close();
	}
    %>

0개의 댓글