[0526] 자바 웹 개발 과정🌞

Let's TECH🧐·2021년 5월 26일
0

자바 웹 개발 과정

목록 보기
19/31
post-thumbnail

⭐자바 웹 개발

이미지 업로드

여러 개의 파일 업로드하기

  • RegController.java
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	request.setCharacterEncoding("UTF-8");
	
	String title = request.getParameter("title");
	String content = request.getParameter("content");
	
	String fileNames = "";
	int fileCount = 0;
	 
	Collection<Part> parts = request.getParts();
	for(Part fpart : parts) {
		if(!fpart.getName().equals("f"))
			continue; // name 값이 f가 아니면 다음 반복으로 건너뜀
		
		if(fpart.getSize() == 0) // 파일을 업로드 안했을 경우 다음 반복으로 건너뜀
			continue;
			
		System.out.printf("name: %s\n", fpart.getName());

		// 입력 스트림에서 파일을 읽고 출력 스트림에서 파일 출력
		// Part fpart = request.getPart("f"); // 파일을 가져오기, 반환 타입이 파트형
		String fileName = fpart.getSubmittedFileName(); // 전송된 파일 이름
		InputStream fis = fpart.getInputStream(); // 파일 스트림
		
		fileNames += fileName + ",";
		fileCount++;
		
		ServletContext application = request.getServletContext(); // 어플리케이션의 저장소 역할, 다른 서블릿이 작업을 이어가려면 동일한 도구, 저장소(ServletContext)가 필요
		String path = "/upload"; // 업로드할 경로
		String realPath = application.getRealPath(path); // 실제 물리 경로를 얻어내줌
		
		File pathFile = new File(realPath); // 파일 만들기
		if(!pathFile.exists()) // 파일이 없으면
			pathFile.mkdirs(); // 경로를 만들어줌
		
		String filePath = realPath + File.separator + fileName; // 운영체제마다 파일 구분자가 다를 수 있음
		FileOutputStream fos = new FileOutputStream(filePath);
		
		System.out.println(realPath);
		
		byte[] buf = new byte[1024];
		int len = 0;
		
		while((len = fis.read(buf, 0, 1024)) >= 0)
			fos.write(buf, 0, len);
		
		fos.flush();
		fos.close();
		fis.close();
	}
	
	if(fileCount > 0) // 파일 개수가 1개 이상일 때만 아래 코드 실행
		fileNames = fileNames.substring(0, fileNames.length()-1); // 파일 이름에서 끝에 쉼표 없애기

파일 다운로드

<!-- forTokens는 잘려진 문자열의 개수만큼 반복해줌 -->
<c:forTokens var="fileName" items="${notice.files}" delims="," varStatus="st"> <!-- varStatus: 상태값 알아내기 -->
	<a download href="/upload/${fileName}">${fileName}</a>
	<c:if test="${!st.last }"> <!-- last가 아닌 경우에 '|' 붙이기 -->
	  |
	</c:if>
</c:forTokens>

프로젝트 관련 이슈

  1. NCLOB 데이터 유형이 포함된 테이블은 GROUP BY로 쿼리를 작동시킬 수 없으니 COUNT, GROUP BY 코드를 작성해서 만든 테이블과 NCLOB 데이터 유형의 컬럼을 조인시켜서 뷰를 새로 만들자!

  2. 이벤트 관련 객체를 사용할 때는 반드시 이벤트 객체를 넘겨주기

request.upload.onprogress = function(e) { // request.upload는 진척도 이벤트를 가지고 있음
  	console.log(`total: ${e.total}, load: ${e.loaded}`) // e.total: 보내야 할 전체 바이트 수, e.loaded: 올라간 바이트 수
  	let status = Math.round(e.loaded*100/e.total) + '%';
  	// e.total : 100 = e.loaded : status

  	progressStatusDiv.firstElementChild.firstElementChild.innerText = status;
  	progressStatusDiv.firstElementChild.firstElementChild.style.width = status;
};
  1. document.onclick은 한 파일에서 여러 번 사용할 수 없다.
profile
Minju's Tech Blog

0개의 댓글