COS이용 API 파일업로드

조승현·2022년 8월 29일
0

GoodsDao.java

public class GoodsDao {	
	// 리턴값 : key값(goods_no) - jdbc 메서드를 사용하면 된다
	public int insertGoods(Connection conn, Goods goods) throws Exception {
		int goodsNo = 0; // keyId
		String sql = "INSERT INTO goods (goods_name, goods_price, update_date, create_date, sold_out) VALUES (?, ?, NOW(), NOW(), ?)";
		PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // 키값을 반환하게 변경
		// stmt setter
		stmt.setString(1, goods.getGoodsName());
		stmt.setInt(2, goods.getGoodsPrice());
		stmt.setString(3, goods.getSoldOut());
		// 디버깅
		System.out.println("GoodsDao.java insertGoods stmt : " + stmt);
		
		// 1) insert 
		stmt.executeUpdate(); // 성공한 row의 수 
		// 2) select last_ai_key from  
		ResultSet rs = stmt.getGeneratedKeys(); // 컬럼명을 알 수 없다! select 문 순서가 첫번째 컬럼이기때문에 받을 수 있다.
		
		if(rs.next()) {
			goodsNo = rs.getInt(1);
		}
		
		if(rs != null) { rs.close(); }
		if(stmt != null) { stmt.close(); }
		
		return goodsNo;
	}
}

GoodsImgDao.java

public class GoodsImgDao {
	// 이미지 삽입
	public int insertGoodsImg(Connection conn, GoodsImg goodsImg) throws Exception {
		// 리턴값 초기화
		int row = 0;
		
		// 쿼리
		String sql = "INSERT INTO goods_img (goods_no, filename, origin_filename, content_type, create_date) VALUES (?, ?, ?, ?, NOW())";
		
		// stmt 초기화
		PreparedStatement stmt = null;
		
		try {
			
			stmt = conn.prepareStatement(sql);
			// stmt setter
			stmt.setInt(1, goodsImg.getGoodsNo());
			stmt.setString(2, goodsImg.getFilename());
			stmt.setString(3, goodsImg.getOriginFilename());
			stmt.setString(4, goodsImg.getContentType());
			// 디버깅
			System.out.println("GoodsImgDao insertGoodsImg stmt : " + stmt);
			
			
			// 쿼리실행
			row = stmt.executeUpdate();
		} finally {
			if(stmt != null) { stmt.close(); }
		}
		
		return row;
	}
}

GoodsService.jsp

public class GoodsService {
	// 서비스 : 트랜잭션 + action이나 dao가 해서는 안되는 일
	// 멤버변수
	private GoodsDao goodsDao;
	private GoodsImgDao goodsImgDao;
	private DBUtil dbUtil;
	// 트랜젝션
	public void addGoods(Goods goods, GoodsImg goodsImg) {
		// 메서드 사용할 객체생성
		this.dbUtil = new DBUtil();
		this.goodsDao = new GoodsDao();

		Connection conn = null;
		
		try {
			conn = new DBUtil().getConnection();
			// 디버깅
			System.out.println("GoodsService.java addGoods conn : " + conn);
			
			// 자동 commit 끄기
			conn.setAutoCommit(false);
			
			goodsDao = new GoodsDao();
			goodsImgDao = new GoodsImgDao();
			
			int goodsNo = goodsDao.insertGoods(conn, goods); // goodsNo가 AI로 자동생성되어 DB입력
			
			if(goodsNo != 0) { // 0이 아니면 키가 있다는 뜻
				// 키값 setter
				goodsImg.setGoodsNo(goodsNo);
				
				if(goodsImgDao.insertGoodsImg(conn, goodsImg) == 0) {
					throw new Exception(); // 이미지 입력실패시 강제로 rollback(catch)절 이동
				}
			}
			
			conn.commit();
		} catch(Exception e) {
			e.printStackTrace();
			// Exception 발생시
			try {
				conn.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

adminGoodsForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="adminHeader.jsp"%>
	<%
       	if(session.getAttribute("id") == null){
       		response.sendRedirect(request.getContextPath() + "/theme/loginForm.jsp?errorMsg=Not logged in");
       		return;
       	} else if(session.getAttribute("id") != null && "customer".equals((String)session.getAttribute("user"))) {
       		// 관리자가 아닌경우 막기
       		response.sendRedirect(request.getContextPath() + "/theme/index.jsp?errorMsg=No permission");
       	}
    %>

    <!-- Open Content -->
    <section class="bg-light">
        <div class="container pb-5">
            <div class="row">
                <!-- col end -->
                <div class="col-lg-12 mt-5 text-center">
                    <div class="card">
                        <div class="card-body">
                            <h1 class="h2">상품등록</h1>
                           	<%
                           		if(request.getParameter("errorMsg") != null){
                           	%>
                           			<span style="color:red">
                           				<%=request.getParameter("errorMsg")%>
                           			</span>
                         	<%
                           		}
                           	%>
                            	<hr>
                            	<form action="<%=request.getContextPath()%>/theme/admin/addGoodsAction.jsp" method="post" enctype="multipart/form-data" id="form">
		                            <table class="table">
					            		<tr>
					            			<th>상품명</th>
					            			<td>
					            				<input type="text" name="goodsName" id="goodsName" class="form-control">
					            			</td>
					            		</tr>
					            		<tr>
					            			<th>상품가격</th>
					            			<td>
					            				<input type="text" name="goodsPrice" id="goodsPrice" class="form-control">
					            			</td>
					            		</tr>
					            		<tr>
					            			<th>이미지</th>
					            			<td>
					            				<input type="file" name="imgFile" id="imgFile" class="form-control">
					            			</td>
					            		</tr>
										<tr>
											<th>품절여부</th>
											<td>
												<select name="soldOut" class="form-control" id="soldOut">
													<option value="defualt">-- 선택 --</option>
			            							<option value="Y">Y</option>
				            						<option value="N">N</option>
				            					</select>
											</td>
										</tr>					            		
					            	</table> 
					            	<button type="button" class="btn btn-dark" id="btn">상품등록</button>
				            	</form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- Close Content -->
   	<script>
		$('#btn').click(function(){
			if($('#goodsName').val().length < 2){
				alert('상품명을 2자이상 기입해주세요');
			} else if($('#goodsPrice').val().length < 1){
				alert('상품가격을 기입해주세요');
			} else if($('#imgFile').val().length < 1){
				alert('상품파일을 등록해주세요');
			} else if($('#soldOut').val() == 'defualt'){
				alert('품절여부를 선택해주세요');
			} else {
				$('#form').submit();
			}
		});
	</script>
<%@ include file="adminFooter.jsp"%>

addGoodsAction.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.oreilly.servlet.*"%>
<%@ page import="com.oreilly.servlet.multipart.*"%>
<%@ page import="service.GoodsService"%>
<%@ page import="vo.Goods"%>
<%@ page import="vo.GoodsImg"%>
<%@ page import="java.io.File"%>
<%@ page import="java.net.URLEncoder"%>
<%
	// 막기
	if(session.getAttribute("id") == null){
		response.sendRedirect(request.getContextPath() + "/theme/loginForm.jsp?errorMsg=Not logged in");
		return;
	} else if(session.getAttribute("id") != null && "customer".equals((String)session.getAttribute("user"))) {
		// 관리자가 아닌경우 막기
		response.sendRedirect(request.getContextPath() + "/theme/index.jsp?errorMsg=No permission");
	}


	// cos 라이브러리 사용하기
	String dir = request.getServletContext().getRealPath("/theme/upload");
	// 디버깅
	System.out.println("addGoodsAction.jsp dir : " + dir);
	
	// 파일사이즈 (용량)
	int max = 10 * 1024 * 1024; // 1024byte -> 1kbyte, 1024kbyte -> 1mbyte
	
	// 원래 request에 래핑 (request, 경로, 파일사이즈, 인코딩, 이름재설정)
	MultipartRequest mRequest = new MultipartRequest(request, dir, max, "UTF-8", new DefaultFileRenamePolicy());
	
	// 입력한 값 받기
	String goodsName = mRequest.getParameter("goodsName");
	int goodsPrice = Integer.parseInt(mRequest.getParameter("goodsPrice"));
	String soldOut = mRequest.getParameter("soldOut");
	
	// 파일 값 받기
	String contentType = mRequest.getContentType("imgFile");
	String originFilename = mRequest.getOriginalFileName("imgFile");
	String filename = mRequest.getFilesystemName("imgFile");
	
	// 디버깅	
	System.out.println("addGoodsAction.jsp goodsName : " + goodsName);
	System.out.println("addGoodsAction.jsp goodsPrice : " + goodsPrice);
	System.out.println("addGoodsAction.jsp soldOut : " + soldOut);
	System.out.println("addGoodsAction.jsp contentType : " + contentType);
	System.out.println("addGoodsAction.jsp originFilename : " + originFilename);
	System.out.println("addGoodsAction.jsp filename : " + filename);
	
	// 객체에 담기
	Goods goods = new Goods();
	// goods setter
	goods.setGoodsName(goodsName);
	goods.setGoodsPrice(goodsPrice);
	goods.setSoldOut(soldOut);
	// 디버깅
	System.out.println("addGoodsAction.jsp goods : " + goods.toString());
	
	
	// 이미지 파일 객체에 담기
	GoodsImg goodsImg = new GoodsImg();
	// goodsImg setter
	goodsImg.setContentType(contentType);
	goodsImg.setOriginFilename(originFilename);
	goodsImg.setFilename(filename);
	// 디버깅
	System.out.println("addGoodsAction.jsp goodsImg : " + goodsImg.toString());
	
	
	// 메서드실행
	GoodsService goodsService = new GoodsService();
	goodsService.addGoods(goods, goodsImg);
	
	
	
	// 이미지 파일이 아닐 경우 막기
	if(!(contentType.equals("image/gif") || contentType.equals("image/png") || contentType.equals("image/jpeg"))){
		// 이미 업로드된 파일을 삭제
		File f = new File(dir + "/" + filename);
		if(f.exists()){ // 파일이 존재하면 삭제
			f.delete();
		}
		
		// 에러메세지
		String errorMsg = URLEncoder.encode("이미지파일만 업로드가능합니다", "UTF-8");
		response.sendRedirect(request.getContextPath() + "/theme/admin/adminGoodsForm.jsp?errorMsg=" + errorMsg);
		return;
	}
	
	// 재요청
	response.sendRedirect(request.getContextPath() + "/theme/admin/adminGoodsList.jsp");
%>
profile
소통을 좋아하는 개발자입니다

0개의 댓글