[backend] Ajax 이용한 회원관리, 파일 업로드

Ajax

비동기 전송

제이쿼리와 Ajax Ajax를 이용하여 개발을 손쉽게 할 수 있도록 미리 여러 가지 기능을 포함해 놓은 개발 환경을 Ajax 프레임워크라고 합니다.

그중에서도 현재 가장 널리 사용되고 있는 Ajax 프레임워크는 바로 제이쿼리(jQuery)입니다.

출처: http://tcpschool.com/ajax/ajax_jquery_ajax

Ajax로 서버쪽에 요청하면 url로 데이터가 다 넘어감

20210619_214519

20210619_215049

컨트롤러가 front와 pojo로 나뉘는데 요청하면 frontController가 핸들러 매핑 거쳐 프런트 컨트롤러가 pojo요청하고 다시 프론트 컨트롤러로 요청, 여기선 jsp 경로 만들어서 요청.

20210619_222428

클라이언트가 서버에 중복확인여부 체크함.

중복확인여부 체크를 자바스크립트에서 제공하는 ajax방식으로 서버에 요청하고 이걸 받아서 응답 화면에 뿌려준다.


Ajax(Asynchronous JavaScript and XML)

동기식 일처리 vs 비동기식 일처리

동기식은 일처리가 끝나야만 다음 일처리가 되지만 비동기는 일처리 진행 와중에도 다른 일처리가 요청 응답이 이뤄진다.

20210619_142627

20210619_142612


20210620_002006

여기서 하나의 객체가 obj에 들어가게 된다.


20210620_021628

이 디렉토리가 이 경로고 아직 만들어지진 않았다

20210619_162015

여기서 이런 방식은 메모리에 저장하기 부담스럽기 떄문에 임시 디렉토리를 만들고 거기에 저장한다.


package kr.bit.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileAddController implements Controller{
	@Override
	public String requestHandler(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String UPLOAD_DIR="file_repo";                                   // \\, /
		String uploadPath=request.getServletContext().getRealPath("")+File.separator+UPLOAD_DIR;
		File currentDirPath=new File(uploadPath); // 업로드할 경로를 File객체로 만들기
		if(!currentDirPath.exists()) {
			currentDirPath.mkdir();
		}
		// 파일을 업로드 할때 먼저 저장될 임시 저장경로를 설정
		// file upload시 필요한 API - commons-fileupload, commons-io
		DiskFileItemFactory factory=new DiskFileItemFactory();
		factory.setRepository(currentDirPath);
		factory.setSizeThreshold(1024*1024);

		String fileName=null;

		ServletFileUpload upload=new ServletFileUpload(factory);
		try {     // items-->FileItem[ ],FileItem[  ],FileItem[ ]
			List<FileItem> items=upload.parseRequest(request); // request안에 여러개의 파일이 업로드 된경우...
			for(int i=0;i<items.size();i++) {
				  FileItem fileItem=items.get(i);
				  if(fileItem.isFormField()) { //폼필드이면
					  System.out.println(fileItem.getFieldName()+"="+fileItem.getString("utf-8"));
				  }else { // 파일이면
					  if(fileItem.getSize()>0) {
						  int idx=fileItem.getName().lastIndexOf("\\"); // \\(Window), /(Linux)
						  //윈도우와 리눅스일 경우 마지막 인덱스 부분을 idx에 넣는다.
						  if(idx==-1) {
							  idx=fileItem.getName().lastIndexOf("/");
						  }
						  fileName=fileItem.getName().substring(idx+1); // 파일이름
						  File uploadFile=new File(currentDirPath+"\\"+fileName);
						  // 파일이 중복체크
						  if(uploadFile.exists()) {
							  fileName=System.currentTimeMillis()+"_"+fileName;
							  uploadFile=new File(currentDirPath+"\\"+fileName);
						  }
						  fileItem.write(uploadFile); //임시경로->새로운경로에 파일 쓰기
					  }
				  }
			}//_for_
		} catch (Exception e) {
			e.printStackTrace();
		}
		// $.ajax()쪽으로 업로드된 최종 파일이름을 전송시켜준다.
		response.setContentType("text/html;charset=euc-kr");
		response.getWriter().print(fileName);		
		return null;
	}
}


20210620_035602

여기 파일이 직접 폴더에 저장되게 된다.

<div class="panel-body">
     <form id="form1" name="form1" class="form-horizontal" method="post">
	  <div class="form-group">
	    <label class="control-label col-sm-2" for="id">아이디:</label>
	    <div class="col-sm-10">
	      <table>
	        <tr>
	          <td><input type="text" class="form-control" id="id" name="id" placeholder="아이디를 입력하세요"></td>
	          <td><input type="button" value="중복체크" onclick="doublecheck()" class="btn btn-warning"></td>
	        </tr>	        
	      </table>
	    </div>
	  </div>
	  <div class="form-group">
	    <label class="control-label col-sm-2" for="pass">비밀번호:</label>
	    <div class="col-sm-10">
	      <input type="password" class="form-control" id="pass" name="pass" placeholder="비밀번호를 입력하세요" style="width: 30%">
	    </div>
	  </div>
	   <div class="form-group">
	    <label class="control-label col-sm-2" for="name">이름:</label>
	    <div class="col-sm-10">
	      <input type="text" class="form-control" id="name" name="name" placeholder="이름을 입력하세요" style="width: 30%">
	    </div>
	  </div>
	    <div class="form-group">
	    <label class="control-label col-sm-2" for="age">나이:</label>
	    <div class="col-sm-10">
	      <input type="text" class="form-control" id="age" name="age" placeholder="나이입력" style="width: 10%">
	    </div>
	  </div>
	    <div class="form-group">
	    <label class="control-label col-sm-2" for="email">이메일:</label>
	    <div class="col-sm-10">
	      <input type="text" class="form-control" id="email" name="email" placeholder="이메일을 입력하세요" style="width: 30%">
	    </div>
	  </div>
	    <div class="form-group">
	    <label class="control-label col-sm-2" for="pass">전화번호:</label>
	    <div class="col-sm-10">
	      <input type="text" class="form-control" id="phone" name="phone" placeholder="전화번호를 입력하세요" style="width: 30%">
	    </div>
	  </div>
	  <div class="form-group">
	    <label class="control-label col-sm-2" for="">첨부파일:</label>
	    <div class="col-sm-10">
	      <input type="file" class="control-label" id="file" name="file">
	    </div>
	  </div>	  

이 폼 부분 서버에 저장해야(업로드를 끝났고) 업로드와 서버에 저장하는 걸 분리해서 한다.







© 2021.03. by yacho

Powered by github