열심히 끝까지

디바이스 융합 자바(Java) day54 - 이미지 업로드 본문

디바이스 융합 자바(Java)기반 풀스택 개발자 양성과정(수업내용)

디바이스 융합 자바(Java) day54 - 이미지 업로드

노유림 2022. 8. 26. 14:56

[ 이미지 업로드 ] >> 제품 등록할 시에 사용

 

1. cos.jar 필요함
import가 되지 않음으로 외부 jar 파일 필요

2. MultipartRequest mr = new MultipartRequest();
   (request,path,maxSize,UTF-8,new DefaultFileRenamePolicy());
   > path : 사용자가 업로드시도한 파일을 어디에 저장할 지, 복붙해내는 식으로 동작
   > maxSize : 바이트 단위 대부분 100000으로 한다고 함
   > UTF-8 : 파일 정보를 읽어들여서 복사 붙여넣기 하는 것을 
   > new DefaultFileRenamePolicy() : 파일 정보를 읽어들여서 복사 붙여넣기 하기 위한 객체


데이터 자체를 보낼거야
데이터 받아서 지정한 위치에 보내줄게!
   >> mr 필요
   >> request값으로는 값을 보지 못함
   >> 보는 방법

// 값 보는 방법
String mid=mr.getParameter("mid");
System.out.println("로그1 ["+mid+"]");
		
// file은 복잡
// collection의 한 일종 = Enumeration
Enumeration<?> file = mr.getFileNames();
if(file.hasMoreElements()) { // 파일이 업로드가 되면?(한개를 올릴수도 있고 아닐 수도 있고)
	String paramName = (String)file.nextElement();
	System.out.println("로그2 ["+paramName+"]");
}

 

 

>> 이미지 업로드.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이미지 업로드</title>
</head>
<body>

<form action="test.do" method="post" enctype="multipart/form-data">
<!-- enctype으로 multipart/form-data를 써야 함 -->
	<input type="text" name="mid">
	<!-- input name을 type과 비슷하게 설정(file)구분해서 실제로 많이 쓰지 않음 -->
	<input type="file" name="file"> 
	<input type="submit" value="확인">
</form>

<hr>

<img alt="${img}" src="images/${img}">

</body>
</html>
package test;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

/**
 * Servlet implementation class Test
 */
@WebServlet("/test.do")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		
		// import가 되지 않음..
		// cos.jar 필요함
		String path="D:\\0607RYO\\workspace\\day54\\src\\main\\webapp\\images";
		int maxSize=100000; // 바이트 단위
		MultipartRequest mr = new MultipartRequest(request,path,maxSize,"UTF-8",new DefaultFileRenamePolicy());
		// 요청정보를 request에 MultipartRequest에 넣었기 때문에 mr을 통해서 봐야한다.
		
		/*
		String mid=request.getParameter("mid");
		String file = request.getParameter("file");
		System.out.println("로그1 ["+mid+"]");
		System.out.println("로그2 ["+file+"]");
		*/
		
		// 값 보는 방법
		String mid=mr.getParameter("mid");
		System.out.println("로그1 ["+mid+"]");
		
		// file은 복잡
		// collection의 한 일종 = Enumeration
		Enumeration<?> file = mr.getFileNames();
		if(file.hasMoreElements()) { // 파일이 업로드가 되면?(한개를 올릴수도 있고 아닐 수도 있고)
			String paramName = (String)file.nextElement();
			System.out.println("파라미터명 ["+paramName+"]");
			
			String serverFileName = mr.getFilesystemName(paramName); // 시스템에 저장되는 이름
			System.out.println("서버에 업로드된 파일 명 ["+serverFileName+"]");
			// 서버에 업로드된 파일 명이 어떤지 출력
			
			// 파일 올리기
			request.getSession().setAttribute("img", serverFileName);
			
			String clientFileName = mr.getOriginalFileName(paramName);
			System.out.println("사용자가 업로드된 파일 명 ["+clientFileName+"]");
			// 사용자가 업로드한 파일 명
			
			String fileType = mr.getContentType(paramName);
			System.out.println("사용자가 업로드된 파일의 타입 ["+fileType+"]");
			// 사용자가 업로드한 파일 타입
			
			long length = mr.getFile(paramName).length();
			System.out.println("사용자가 업로드된 파일의 크기 ["+length+"]");
			// 사용자가 업로드한 파일 크기 바이트 단위
			
			// 존재하는 이름의 파일을 올리면 이름뒤에 1이 붙어서 나옴
			// 그 뒤로 앞의 파일을 계속 올리면 숫자가 계속 커지면서 올라감 
			
		}
		// scope 내장객체에 저장해야 함
		
		response.sendRedirect("NewFile.jsp");
	}

}