카테고리 없음

파일첨부

logloglog 2021. 1. 5. 14:59

모델1

jsp 바로 호출하는 경우 (jsp가 거의 서블릿 .. 여기에 다 때려넣) 

모델2

무조건 컨트롤러 가야함.. 모델바탕으로 화면렌더링하는쪽으로 던져가지고 뷰에서 화면 던지도록

 

파일업로드 : 인코딩을 가장 고민해야함

멀티파트이기떄문에 기존방식으로는 파싱ㅂ불가하기때문에 특정 라이브러리 이용해서해야함

리퀘스트래퍼 이용해서 리퀘스트객체대신 리퀘스트래퍼객체 썼음

인서트할때마다 기존에 있는것보다 하나 증가시키려고 할라고

atch_file_id 도 기본키역할이지만 sn인 순번도 기본키처럼 쓰일거임

복붙

dao 만들자

(공통서비스)

kr.or.ddit.common.dao

package kr.or.ddit.common.dao;

import java.sql.SQLException;
import java.util.List;

import kr.or.ddit.vo.AtchFileVO;

public interface IAtchFileDao {

	/**
	 * 첨부파일 정보 저장
	 * @param fileVO
	 * @return
	 * @throws SQLException
	 */
	public int insertAtchFile(AtchFileVO fileVO) throws SQLException;

	/**
	 * 첨부파일 목록 조회
	 * @param fileVO
	 * @return
	 * @throws SQLException
	 */
	public List<AtchFileVO> getAtchFileList(AtchFileVO fileVO) throws SQLException;
	
	/**
	 * 첨부파일 세부 정보 조회 메서드
	 * @param fileVO
	 * @return
	 * @throws SQLException
	 */
	public AtchFileVO getAtchFileDetail(AtchFileVO fileVO) throws SQLException;

	
}

 

이제 impl

 

 

아래께 딱 한개.. 순번까지 지정해서

package kr.or.ddit.common.dao;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.ibatis.sqlmap.client.SqlMapClient;

import kr.or.ddit.util.SqlMapClientFactory;
import kr.or.ddit.vo.AtchFileVO;

public class AtchFileDaoImpl implements IAtchFileDao{

	private static IAtchFileDao dao;
	private SqlMapClient smc;
	private AtchFileDaoImpl() {
		smc = SqlMapClientFactory.getInstance();
	}
	
	public static IAtchFileDao getInstance() {
		if(dao == null) {
			dao = new AtchFileDaoImpl();
		}
		return dao;
	}
	
	@Override
	public int insertAtchFile(AtchFileVO fileVO) throws SQLException {
		
		int cnt = 0;
		
		Object obj = smc.insert("atchFile.insertAtchFile",fileVO);
		if(obj == null) {
			cnt = 1;
		}
		
		return cnt;
	}

	@Override
	public List<AtchFileVO> getAtchFileList(AtchFileVO fileVO) throws SQLException {
		List<AtchFileVO> atchList = Collections.emptyList();
//		List<AtchFileVO> atchList = null; //뭘로하든 괯낳음
		atchList =  smc.queryForList("atchFile.getAtchFileList",fileVO);
		
		return atchList;
	}

	@Override
	public AtchFileVO getAtchFileDetail(AtchFileVO fileVO) throws SQLException {
		
		AtchFileVO atchFileVO = (AtchFileVO) smc.queryForList("atchFile.getAtchFileDetail",fileVO);
		return atchFileVO;
	}

}
package kr.or.ddit.common.dao;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.ibatis.sqlmap.client.SqlMapClient;

import kr.or.ddit.util.SqlMapClientFactory;
import kr.or.ddit.vo.AtchFileVO;

public class AtchFileDaoImpl implements IAtchFileDao{

	private static IAtchFileDao dao;
	private SqlMapClient smc;
	private AtchFileDaoImpl() {
		smc = SqlMapClientFactory.getInstance();
	}
	
	public static IAtchFileDao getInstance() {
		if(dao == null) {
			dao = new AtchFileDaoImpl();
		}
		return dao;
	}
	
	@Override
	public int insertAtchFile(AtchFileVO fileVO) throws SQLException {
		
		int cnt = 0;
		
		Object obj = smc.insert("atchFile.insertAtchFile",fileVO);
		if(obj == null) {
			cnt = 1;
		}
		
		return cnt;
	}

	@Override
	public List<AtchFileVO> getAtchFileList(AtchFileVO fileVO) throws SQLException {
		List<AtchFileVO> atchList = Collections.emptyList();
//		List<AtchFileVO> atchList = null; //뭘로하든 괯낳음
		atchList =  smc.queryForList("atchFile.getAtchFileList",fileVO);
		
		return atchList;
	}

	@Override
	public AtchFileVO getAtchFileDetail(AtchFileVO fileVO) throws SQLException {
		
		AtchFileVO atchFileVO = (AtchFileVO) smc.queryForList("atchFile.getAtchFileDetail",fileVO);
		return atchFileVO;
	}

}

 

 

 

package kr.or.ddit.common.service;

import java.io.File;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import org.apache.commons.fileupload.FileItem;

import kr.or.ddit.common.dao.AtchFileDaoImpl;
import kr.or.ddit.common.dao.IAtchFileDao;
import kr.or.ddit.util.FileUploadRequestWrapper;
import kr.or.ddit.vo.AtchFileVO;

public class AtchFileServiceImpl implements IAtchFileService{

	private static IAtchFileService fileService;
	private IAtchFileDao fileDao;
	
	private AtchFileServiceImpl() {
		fileDao = AtchFileDaoImpl.getInstance();
	}
	
	public static IAtchFileService getInstance() {
		if(fileService == null) {
			fileService = new AtchFileServiceImpl();
		}
		return fileService;
	}
	
	@Override
	public AtchFileVO saveAtchFile(FileItem item) throws Exception {
		File uploadDir = new File(FileUploadRequestWrapper.UPLOAD_DIRECTORY);
		if(!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		//여기서부터 슬슬 저장작업
		String orignFileName = new File(item.getName()).getName();
		long fileSize = item.getSize();
		String storeFileName = "";
		String filePath = "";
		
		File storeFile = null;
		
		do {
			storeFileName = UUID.randomUUID().toString().replace("-", ""); //name을 임의로 만들어보려고함
			filePath = FileUploadRequestWrapper.UPLOAD_DIRECTORY + File.separator + storeFileName;
			storeFile = new File(filePath);
		}while(storeFile.exists());// 파일명이 중복안될때까지..  중복이 아니어야 두와일끝남
		
		//확장명 추출
		String fileExtension = orignFileName.lastIndexOf(".") < 0 ? "" : orignFileName.substring(orignFileName.lastIndexOf(".")+1);
		item.write(storeFile);//업로드 파일 저장
		
		//파일업로드 잘 됐다고치고 이제 db저장
		//파일 젖아 서비스 호출
		AtchFileVO fileVO = new AtchFileVO();
		fileVO.setStreFileNm(storeFileName);
		fileVO.setFileSize(fileSize);
		fileVO.setOrignlFileNm(orignFileName);
		fileVO.setFileStreCours(filePath);
		fileVO.setFileExtsn(fileExtension);
		
		fileDao.insertAtchFile(fileVO);//세부파일정보저장

		item.delete();//임시업로드 파일 삭제하기
		
		return fileVO;
	}

	@Override
	public List<AtchFileVO> getAtchFileList(AtchFileVO fileVO) throws SQLException {
		//그냥 dao에 있는거 호출하면 됨
		
		return fileDao.getAtchFileList(fileVO);
	}

	@Override
	public AtchFileVO getAtchFileDetail(AtchFileVO fileVO) throws SQLException {
		return fileDao.getAtchFileDetail(fileVO);
	}
	
}

 

실제 등록이 되는지..

 

 

 

 

 


이제 읽어오자

 

 


이제 다운받자

package kr.or.ddit.common.handler;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.ddit.common.dao.AtchFileDaoImpl;
import kr.or.ddit.common.dao.IAtchFileDao;
import kr.or.ddit.member.handler.CommandHandler;
import kr.or.ddit.vo.AtchFileVO;

public class FileDownloadHandler implements CommandHandler{
	
	private IAtchFileDao fileDao = AtchFileDaoImpl.getInstance();

	@Override
	public boolean isRedirect(HttpServletRequest req) {
		return false;
	}

	@Override
	public String process(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		long fileId = req.getParameter("fileId") != null ?  Long.parseLong(req.getParameter("fileId")) : -1;
		int fileSn = req.getParameter("fileSn") != null ?  Integer.parseInt(req.getParameter("fileSn")) :1;
		
		//파일 정보 조회
		AtchFileVO fileVO = new AtchFileVO();
		fileVO.setAtchFileId(fileId);
		fileVO.setFileSn(fileSn);
		
		fileDao.getAtchFileDetail(fileVO);
				
				//파일 다운로드 처리를 위한 응답헤더 정보 설정하기
				resp.setContentType("application/octet-stream");
				//마인타입을 application/octet-stream 으로 하면 이진타입의 어쩌구.. 
				resp.setHeader("Content-Disposition", "attachment; filename=\""+fileVO.getOrignlFileNm()+"\"");
				
				/**
				 * Content-Disposition 헤더(를 이용해서 파일다운과 업로드에대한 정보를 표현한다)에 대하여..
				 * 1. response header에서 사용되는 경우 ... ex)파일 다운로드
				 * Content-Disposition : inline (default) 인라인:브라우저내에서보는것...
				 * Content-Disposition : attachment // 파일 다운로드  어태치먼트 : 첨부하다..
				 * Content-Disposition : attachment; filename="파일명" //특정한 이름을 지어주고싶은경우
				 * 이 파일명으로 브라우저에서 저장하겠다..는말임
				 * 
				 * 파일업로드할때는 필드값을 의미하는 값이 더 들어감
				 * 2. multipart body를 위한 헤더정보로 사용되는 경우.. ex)파일 업로드
				 * Content-Disposition : form-data
				 * Content-Disposition : form-data; name="filedName"
				 * Content-Disposition : form-data; name="filedName"; filename="파일명"
				 */
				
				
				BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:/D_Other/"+fileVO.getFileStreCours()));
				BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream());
				
				int bytes = 0; //읽은 바이트 수
				while((bytes = bis.read()) != -1) {
					bos.write(bytes);
				}
				
				bis.close();
				bos.close();
		
		return null;
	}

}

ㅅ사행

핸들러 등록해야함

 

select.jsp

<tr>
			<td>첨부파일 : </td>
			<td>
			<%if(atchFileList != null){
				for(AtchFileVO fileVO : atchFileList){
			%>
			<div>
				<a href="<%=request.getContextPath() %>/fileDownload.do?fileId=<%=fileVO.getAtchFileId()%>&fileSn=<%=fileVO.getFileSn()%>"><%=fileVO.getOrignlFileNm() %></a>
			</div>			
			 <%
				}//for
			}//if
				%>
			</td>
		</tr>