파일업로드4

  • 파일업로드

    • 테이블에 직접저장 : 파일
    • 테이블의 컬럼 : 파일이름저장, 업로드폴더(권장)
  • 파일기능첨부

    • 회원테이블 : 사진이미지(1개) 파일첨부 -> 회원테이블에 컬럼추가

    • 게시판 : 파일첨부(파일이 여러개) -> 게시판테이블에 컬럼을 추가하지 않는다

      게시판의 경우 파일첨부 테이블 독립적으로 생성

테이블 생성
-- 파일첨부
CREATE TABLE TBL_ATTACH(
    UUID        VARCHAR2(100)   CONSTRAINT PK_ATTACH PRIMARY KEY,
    UPLOADPATH  VARCHAR2(200)   NOT NULL,
    FILENAME    VARCHAR2(100)   NOT NULL,
    FILETYPE    CHAR(1) DEFAULT 'I',
    BNO         NUMBER,
    FOREIGN KEY (BNO) REFERENCES TBL_BOARD(BNO)
);
BoardAttachVO 생성
package com.demo.domain;

import lombok.Data;

@Data
public class BoardAttachVO {

	// uuid, uploadPath, fileName, fileType, bno
	
	private String uuid;
	private String uploadPath;
	private String fileName;
	private String fileType;
	private Long bno;
	
}
BoardVO에 추가
	//파일첨부 클래스
	private List<BoardAttachVO> attachList;
write.jsp에 넣기
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.88.1">
    <title>Pricing example · Bootstrap v4.6</title>

    <style>
      .uploadResult {
        width: 100%;
        background-color: gray;
      }
      
      .uploadResult ul {
        display: flex;
        flex-flow: row;
        justify-content: center;
        align-items: center;
      }
      
      .uploadResult ul li {
        list-style: none;
        padding: 10px;
      }
      
      .uploadResult ul li img {
        width: 100px;
      }
    </style>
    <style>
      .bigPictureWrapper {
        position: absolute;
        display: none;
        justify-content: center;
        align-items: center;
        top:0%;
        width:100%;
        height:100%;
        background-color: gray; 
        z-index: 100;
      }
      
      .bigPicture {
        position: relative;
        display:flex;
        justify-content: center;
        align-items: center;
      }
    </style>

    <link rel="canonical" href="https://getbootstrap.com/docs/4.6/examples/pricing/">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	  <script>
	    // 정규식-문자열을 대상으로 패턴문법을 이용하여, 패턴에 일치되는지 여부를 확인
      let regex = new RegExp("(.*?)\.(exe|sh|zip|alz)$");
      let maxSize = 5 * 1024 * 1024; //5mb

      // 파일정보가 출력되는 태그위치 설정. 선택자 태그가 인식이 안됨
      // let uploadResult = $(".uploadResult ul");


      // 업로드 파일크기, 확장자 체크
      function checkExtension(fileName, fileSize){

          if(fileName >= maxSize){
              alert("파일 크기용량 초과");
              return false;
          }

          if(regex.test(fileName)){
              alert("해당 종류의 파일은 업로드 불가");
              return false;
          }

          return true;
      }


      function showUploadedFile(uploadResultArr){
        let str = ""; // 파일정보를 html태그와 함께 구성

        $(uploadResultArr).each(function(i,obj){

      // private String uuid; // 중복되자 않는 파일명
	    // private String uploadPath; // 날짜를 이용한 업로드 폴더명
      // private String fileName; // 클라이언트에서 보낸 파일명
	    // private boolean image; // 이미지 파일구분. true -> 이미지, false -> 이미지가 아닌 파일
            

            if(!obj.image) { // 일반파일
                let fileCalPath = encodeURIComponent(obj.uploadPath + "/" + obj.uuid + "_" + obj.fileName);
                
                // console.log("일반파일경로 : " + fileCalPath);
                // console.log("일반파일경로 : " + encodeURIComponent(fileCalPath));

                str += "<li><div><a href='/upload/download?fileName=" + fileCalPath + "'><image src='/resources/img/attach.png'>" +
                    obj.fileName + "</a><span style='cursor:pointer;' data-file=\'" + fileCalPath + "\' data-type='file'> X </span></div></li>";



            } else { // 이미지파일. 섬네일 이미지를 사용
                let fileCalPath = encodeURIComponent(obj.uploadPath + "/" + "s_" + obj.uuid + "_" + obj.fileName); // 섬네일 이미지 경로
                let originPath = obj.uploadPath + "\\" + obj.uuid + "_" + obj.fileName; // 원본이미지 경로

                console.log(fileCalPath);

                originPath = originPath.replace(new RegExp(/\\/g), "/"); // \를 /로 바꾸는 작업

                console.log(fileCalPath);


                str += "<li><a href=\"javascript:showImage('" + originPath + "')\"><img src='display?fileName=" + fileCalPath + "'></a>" +
                  "<span style='cursor:pointer;' data-file=\'"  + fileCalPath + "\' data-type='image'> X </span></li>";
            }
        });

        // 파일정보가 삽입되는 과정.
        // ready()이벤트 메서드는 브라우저가 태그를 읽고 난 이후 동작하는 특징
        $(".uploadResult ul").append(str);
      }


      // fileCalPath 파라미터 : 날짜 폴더경로를 포함한 원본이미지 파일명
      function showImage(fileCalPath){
          $(".bigPictureWrapper").css("display", "flex").show();

          $(".bigPicture").html("<img src='display?fileName=" + fileCalPath + "'>").animate({width: '100%', height: '100%'}, 1000);
      }

      $(document).ready(function(){

        // <input type="file"> onChange 이벤트
        // 1) 파일첨부 이벤트
        $("input[type='file']").change(function(){

          console.log("파일선택");

          let formData = new FormData();
          let inputFile = $("input[name='uploadfile']");

          let files = inputFile[0].files;

          for(let i=0; i<files.length; i++){

            if(!checkExtension(files[i].name, files[i].size)) {
              return false;
            }

            formData.append("uploadFile", files[i]);
          }

          $.ajax({
            url: '/upload/uploadAjaxAction',
            processData: false,
            contentType: false,
            data: formData,
            type: 'POST',
            dataType: 'json',
            success: function(result){ // 파일정보
              console.info(result);

              showUploadedFile(result);

            }
          });

        });

        // 2) 전송버튼 클릭 (파일첨부 정보를 참조)
        let formObj = $("#boardForm");

        // 글쓰기 전송버튼
        $("#button[type='submit']").on("click", function(e){
          e.preventDefault(); // submit 기능이 취소

          // 첨부된 파일정보 태그작업추가


          formObj.submit();
        });


      });
	  </script>

    <!-- Bootstrap core CSS -->
    <link href="/resources/css/bootstrap.min.css" rel="stylesheet">


    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>

    
    <!-- Custom styles for this template -->
    <link href="/resources/css/pricing.css" rel="stylesheet">
  </head>
  <body>
    
<%@ include file="/WEB-INF/views/include/header.jsp" %>

<%@ include file="/WEB-INF/views/include/carousel.jsp" %>
<div class="container">
  <div class="row">
    <div class="col-12">
      <h3>게시판 글쓰기</h3>
      <form id="boardForm" method="post" action="write">
        <div class="form-group">
          <label for="title">제목</label>
          <input type="text" class="form-control" id="title" name="title">
        </div>
        <div class="form-group">
          <label for="content">내용</label>
          <textarea class="form-control" id="content" rows="3" name="content"></textarea>
          </div>
        <div class="form-group">
          <label for="writer">작성자</label>
          <input type="text" class="form-control" id="writer" name="writer">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </div>

  <div class="row">
    <div class="col-12">
      <h6>File Attach</h6>
      <div class="uploadDiv">
        <input type="file" name="uploadfile" multiple>
      </div>
    
      <!-- 업로드된 파일정보를 출력 -->
      <div class="uploadResult">
          <ul></ul>
      </div>
    </div>
  </div>




  <%@ include file="/WEB-INF/views/include/footer.jsp" %>
</div>


    
  </body>
</html>

image-20220701173430346

댓글남기기