본문 바로가기
프로그램/스프링

jsp 멀티 첨부파일 생성& 삭제

by cbwstar 2023. 6. 29.
728x90
반응형

제이쿼리 & jsp 화면에서 멀티 첨부파일 등록 및 다운로드 스프링 연동

jsp 파일에서 첨부파일 선택 하는 부분입니다.

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<section class="contents">

	<section class="subContents">
		
		<!-- SUB TITLE -->
		<section class="sub-title">
			<h2 class="subTit" id="pevMove">문의하기</h2>
		</section>
		<!-- SUB TITLE -->


		<!-- SUB CONTENT -->
		<article class="sub-content">
			
			<form id="noticeInsertForm">  
				<section class="board-write">
					<dl>
						<dt><label for="bbsctt_sj">제목</label></dt>
						<dd><input id="bbsctt_sj" name="bbsctt_sj" type="text" class="w100p" />
							<input type="hidden" id="bbsctt_no" name="bbsctt_no" title="번호" style="width:90%"/>
							<input type="hidden" id="register_id" name="register_id" title="작성자"/>
							<input type="hidden" id="regist_dt" name="regist_dt"/>
							<input type="hidden" id="ntt_inqire_co" title="조회수"/>
							<input class="form-control" value="" type="hidden" style="font-size:14px;" id="ntce_end_dt" name="ntce_end_dt"/> 
							<input class="form-control" value="" type="hidden" style="font-size:14px;" id="ntce_begin_dt" name="ntce_begin_dt"/>
						</dd>
						<dt><label for="bbsctt_cn">내용</label></dt>
						<dd><textarea id="bbsctt_cn" name="bbsctt_cn" title="내용" class="w100p" rows="10"></textarea></dd>
						<dt><label>문의 내용을 최대한 상세히 적어 주세요</label></dt> 
						<br/>
						<h5>첨부파일</h5>
						<dd>
						  <!-- 첨부파일 -->
						  <div class="file_input">
						     <label class="fileAtchBtn" >
						       파일선택
						       <input name="file" id="file_0" type="file" style="display:none;" />
						     </label>
						  </div>
						  <div id="fileList"></div>
						</dd>
					</dl>
				</section>
				<input type="hidden" id="s_bbs_id"            name="s_bbs_id"            value="2"/> 
				<input type="hidden" id="sessionId" name="sessionId" />
			</form>
			<button type="button" class="inquiryBtn" id="insertQna">문의등록</button>
		</article>
		<!-- SUB CONTENT -->

	</section>
	
</section>

<script type="text/javascript" src="/invakoLib/js/paging.js"></script>
<script type="text/javascript">

var pageId =  "noticeList";
var _recordCountPerPage = 0;
var _currentPage        = 0;
//var $List= $('#table_list');  
var nowDate = '';
//var writer = user_id;

$(document).ready(function() {
	
	$('#insertQna').on('click', function(){
		if($('#bbsctt_sj').val()==""||$('#bbsctt_sj').val()==null||$('#bbsctt_sj').val()=="undefined"){
			alert("제목을 입력 해주세요.");
			return false;
		}else if($('#bbsctt_cn').val()==""||$('#bbsctt_cn').val()==null||$('#bbsctt_cn').val()=="undefined"){
			alert("내용을 입력 해주세요.");
			return false;
		}else{
			_setinsertQna();
		}
	});
	var fileCnt = 0;
	$(document).on('change','input[type=file]', function(){
		//선택한 파일명 붙이기
		$('#fileList').append(
		  $('<p/>').attr('data-index', fileCnt).text(this.files[0].name + ' ['+this.files[0].size+' byte] ').addClass('fileatt').append(
		    $('<button/>').attr('type','button').addClass('btn-td-delete').text('삭제').attr('onclick','fnAtchFileDelete(this)')
		    ).css('margin','5px 0')
		  )
		  
		  fileCnt++;
		  //새로운 파일 INPUT 붙이기
		  var newFile = $('<input/>').attr('type','file').attr('name','file_'+fileCnt).attr('id','file_'+fileCnt).attr('style','display:none');
		//  newFile.style.display = 'none';
		  
		  $(this).before(newFile);
		  //현재 파일 INPUT 숨기기
		  this.style.position = 'absolute';
		  this.style.left = '-1000px';
		  this.style.top = '-1000px';
		  this.style.display = 'none';
		  this.style.visibility = 'hidden';
		  this.style.width = '0';
		  this.style.height = '0';
		  this.style.overflow = 'hidden';
	});
	

	
}); 

//첨부파일 삭제
function fnAtchFileDelete(obj) {
	if($(obj).parent().attr('data-index')) { //index가 있는 값은 새로 추가된 파일
	  $('#file_'+ $(obj).parent().attr('data-index')).remove();
	}
	
	$(obj).parent().remove(); //p태그 삭제
	
}

/* 문의하기 등록 */
var _setinsertQna =function(){
	
	var formData = new FormData();
	// 넘길 데이타를 담아준다.
	var data = {
		"bbscttSj" : $("#bbsctt_sj").val(),	
		"bbscttCn" : $("#bbsctt_cn").val(),
	}
	
	// input 파일건수 
	$('input[type=file]').each(function(){
		if(this.files.length > 0) {		
			console.log(" this.files[0] :::", this.files[0]);
			formData.append('file', this.files[0]);
		}
	})
	
	// 'key'라는 이름으로 위에서 담은 data를 formData에 append한다. type은 json  
    formData.append('key', new Blob([ JSON.stringify(data) ], {type : "application/json"}));
	
	// ajax 처리 부분 * 
	$.ajax({
	      url: '/logFarm/saveNotice.json',
	      type: "post",
	      data: formData,
	      contentType: false,               
	      processData: false,               
	      enctype : 'multipart/form-data', 
	      success:function(jObj){
				alert("문의 사항이 등록 되었습니다.");
				location.href="/logFarm/qnaList.do";
		   },  
			error:function(request,status,error){   
				alert('[' + request.status + '] 에러가 발생하였습니다.', '에러발생');
				return false;
			}
	});
	
};

</script>

자바 소스

     /*
 	 * Controller.java
 	 * */
	
	@RequestMapping(value="/saveNotice.json", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveNotice( HttpServletRequest request, @RequestPart(value = "key") Map<String, Object> param,  @RequestPart(value = "file",required = false) List<MultipartFile> fileList) throws Exception {
			
		logger.debug("param:" + param);
		logger.debug("fileList:" + fileList);
	  
		logFileService.saveAtachNotice(param,fileList);
	  
	  Map<String, Object> map = new HashMap<String, Object>();
	  return map;
	
	}
/*
 Service.java
*/

@Override
	public void saveAtachNotice(Map<String, Object> tbBbscttMap, List<MultipartFile> fileList) throws Exception {
		//첨부파일이 있는경우
		if(fileList.size()>0) {
			List<FileItem> list = FileUploadUtil.fileUpload(fileList);
			System.out.println("list" + list);
			
			int size = list.size();
			
			/* 첨부파일번호를 가지고 온다 */
			int atchFileNo = bbscttDAO.selectAtchFileKey();
			
			for (int i=0; i<size; i++) {
				//1. 첨부파일 정보
				FileItem fileItem= list.get(i);
				Map<String,Object> tbFileAttachMap = new HashMap<String, Object>();
				
				tbFileAttachMap.put("atchFileNo", atchFileNo);
				tbFileAttachMap.put("seqNo", i+1);
				tbFileAttachMap.put("fileName",fileItem.getFileName());
				tbFileAttachMap.put("finalFileName",fileItem.getFinalFileName());
				tbFileAttachMap.put("path",fileItem.getPath());
				tbFileAttachMap.put("extention",fileItem.getExtention());
				tbFileAttachMap.put("size",fileItem.getSize());
				tbFileAttachMap.put("mimeType",fileItem.getMimeType());
				tbFileAttachMap.put("registerId",tbBbscttMap.get("registerId"));
				//2. 첨부파일 등록
				bbscttDAO.insertTbFileAttach(tbFileAttachMap);
			}
			//3. 문의사항 등록
			tbBbscttMap.put("atchFileNo", atchFileNo);
			tbBbscttMap.put("bbsId", 2);
			bbscttDAO.insertTbBbscttM(tbBbscttMap);
			
		} else {
			//3. 문의사항 등록
			tbBbscttMap.put("bbsId", 2);
			bbscttDAO.insertTbBbscttM(tbBbscttMap);
		}
	}
/*
FileUploadUtil.java
*/

package logfarm.admin.file.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.jasypt.commons.CommonUtils;
import org.springframework.web.multipart.MultipartFile;

import egovframework.com.cmm.service.EgovProperties;

public class FileUploadUtil {
	public static String UPLOAD_PATH = EgovProperties.getProperty("Globals.fileStorePath").trim(); 
	
				 
    public static FileItem saveFileInDir(MultipartFile multipartFile, String gbn) throws IOException {
    	
    	if(gbn.equals("image")) {
    		UPLOAD_PATH = EgovProperties.getProperty("Globals.imageStorePath").trim(); 
    	}
    	
        Path uploadDirectory = Paths.get(UPLOAD_PATH);
 
        String fileId = createUUID();
        String fileName = multipartFile.getOriginalFilename();
        
        /* 파일확장자 가져오기 */
        int pos = fileName.lastIndexOf(".");
        String extention = fileName.substring(pos+1);
 
        String finalFileName = createUUIDfileName(extention);
        String mimeType = multipartFile.getContentType();
 
        //디렉토리 존재여부
        File destination = new File(UPLOAD_PATH);
        
        if( destination.exists() == false) {
        	boolean mkdirs = destination.mkdirs();
	            	
        }

        long size = multipartFile.getSize();
 
 
        System.out.println("fileName: " + fileName);
        System.out.println("newFIleName: " + finalFileName);
        System.out.println("extention: " + extention);
        System.out.println("size: " + size);
 
        try (InputStream inputStream = multipartFile.getInputStream()) {
            Path filePath = uploadDirectory.resolve(finalFileName);
 
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
 
            FileItem finalFileItem = new FileItem(
            		fileName,
                    finalFileName,
                    size,
                    mimeType,
                    extention,
                    UPLOAD_PATH
             );
 
            return finalFileItem;
         } catch (IOException ioe) {
            throw new IOException("Error on saving uploaded file: " + fileName, ioe);
         }
     }
    public static String createUUID() {
        UUID uuid = UUID.randomUUID();
        String fileId = uuid.toString();
        return fileId;
     }
 
    public static String createUUIDfileName(String extention) {
        return createUUID() + "." + extention;
     }
    
	/**
     * 파일특수문자 변환
     * @return
     */
     public static String removedFileTraversal(String fileName) {
    	   	 
         if(fileName == null) {
             return null;
         }
         fileName = fileName.replaceAll ("\\.\\./","");
         fileName = fileName.replaceAll ("\\\\","");
         fileName = fileName.replaceAll ("&","");
        
         return fileName;
     }
     
     
   //jsp 파일 업로드 
     public static List<FileItem> fileUpload( List<MultipartFile> fileList) throws Exception{ 
  
       List<FileItem> list = new ArrayList<FileItem>(); 

       for(MultipartFile mf : fileList){

    	   FileItem resultFileItem =  (FileItem) FileUploadUtil.saveFileInDir(mf,"file");
    	   
    	   System.out.println("resultFileItem  : " + resultFileItem);

	       list.add(resultFileItem); 

       }
       return list; 
     }
}
/*
FileItem.java
*/

package logfarm.admin.file.util;

public class FileItem {
	public FileItem() {}
	 
    public FileItem(String fileName, String finalFileName, long size, String mimeType, String extention, String path) {
        this.fileName = fileName;
        this.finalFileName = finalFileName;
        this.size=size;
        this.mimeType = mimeType;
        this.extention = extention;
        this.path = path;
        this.status = true;
     }

    private String fileName;
 
    private long size;
 
    private String mimeType;
 
    private String finalFileName;
 
    private String extention;
    
    private String path;

    private Boolean status;

	public String getFileName() {
		return fileName;
	}

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

	public long getSize() {
		return size;
	}

	public void setSize(long size) {
		this.size = size;
	}

	public String getMimeType() {
		return mimeType;
	}

	public void setMimeType(String mimeType) {
		this.mimeType = mimeType;
	}

	public String getFinalFileName() {
		return finalFileName;
	}

	public void setFinalFileName(String finalFileName) {
		this.finalFileName = finalFileName;
	}

	public String getExtention() {
		return extention;
	}

	public void setExtention(String extention) {
		this.extention = extention;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public Boolean getStatus() {
		return status;
	}

	public void setStatus(Boolean status) {
		this.status = status;
	}

	@Override
	public String toString() {
		return "FileItem [fileName=" + fileName + ", size=" + size + ", mimeType=" + mimeType + ", finalFileName="
				+ finalFileName + ", extention=" + extention + ", path=" + path + ", status=" + status + "]";
	}
    
    


    
}

 

728x90
반응형

댓글



"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

loading