Ex) 로그인 시 아이디 정보를 저장 checkbox 표현 시

 

1. 세션에 저장된 login정보 가져오기

(Spring 에서 세션으로 저장하기 : @SessionAttributes + Model 객체 방식으로도 가능하다)

 

받아올 때 @ModelAttribute 객체로 받아오고 + 클래스에 @SessionAttributes({객체명}) 선언으로

model 객체를 session으로 사용한다.

 

2. 쿠키 생성

Cookie cookie = new Cookie("saveId" , 객체.getId() );

 

3. 쿠키 유효기간 설정 + 사용될 경로 설정

				if(아이디저장 체크박스 value !=null) {
					//아이디 저장 체크 시
					cookie.setMaxAge(60*60*24*30);
				}
				else {
					cookie.setMaxAge(0);
                    //체크 해제 시 유효기간 = 0
                    // 가지고 있던 쿠키가 사라진다
				}
				cookie.setPath(req.getContextPath());
                (HttpServletRequest 객체로 루트를 가져온다
                
                (HttpServletResponse 객체로 전송한다)
				resp.addCookie(cookie);

썸머노트 실행 + 이미지 별도처리 JS

//썸머노트 실행 함수
        function notesummer(){
            //썸머노트 실행
            $('#summernote').summernote({
            lang:"ko-KR",
            placeholder: '내용을 입력해주세요',
            tabsize: 2,
            width : 1200,
            height: 600,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'underline', 'clear']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ],
            callbacks : { 
                //onImageUpload = 이미지 업로드시 작동하는 콜백함수
                onImageUpload : function(files, editor, welEditable) {
            // 파일 업로드(다중업로드를 위해 반복문 사용)
                for (var i = files.length - 1; i >= 0; i--) {
                        uploadSummernoteImageFile(files[i],
                        this);
                        }
                }
            }//end callbacks 
            });
            // 이미지 업로드시 ajax로 파일 업로드를 하고 성공 후 파일 경로를 return받음
            function uploadSummernoteImageFile(file, editor) {
            data = new FormData();
            data.append("file", file);
            $.ajax({
                url : "summernoteImage",
                data : data,
                type : "POST",
                dataType : 'JSON',
                contentType : false,
                processData : false,
                success : function(data) {
                    //항상 업로드된 파일의 url이 있어야 한다.
                    $(editor).summernote('insertImage', contextPath+data.url);
                }
            });
            } 
        }

 

 

이미지 처리 컨트롤러 코드

	//썸머노트 이미지처리 ajax
	@PostMapping("summernoteImage")
	//썸머노트 이미지 처리
	public String insertFormData2(
			@RequestParam(value="file", required=false) MultipartFile file,HttpSession session
			) {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<String, String>();
		// 2) 웹 접근 경로(webPath) , 서버 저장 경로 (serverPath)
		String WebPath = "/resources/images/summernoteImages/"; //DB에 저장되는 경로
		String serverPath = session.getServletContext().getRealPath(WebPath);
		String originalFileName=file.getOriginalFilename();
		String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
		String savedFileName = UUID.randomUUID() + extension;	//저장될 파일 명
		File targetFile = new File(serverPath + savedFileName);	
		try {
			InputStream fileStream = file.getInputStream();
			FileUtils.copyInputStreamToFile(fileStream, targetFile);	//파일 저장
			// contextroot + resources + 저장할 내부 폴더명
			map.put("url", WebPath+savedFileName);
			map.put("responseCode", "success");
		} catch (IOException e) {
			FileUtils.deleteQuietly(targetFile);	//저장된 파일 삭제
			map.put("responseCode", "error");
			e.printStackTrace();
		}
		return gson.toJson(map);
	}

'API 적용해보기' 카테고리의 다른 글

스프링에 네이버로그인 적용해보기  (0) 2022.01.16

스프링에서는 MultipartFile 객체를 제공한다

 

1. 라이브러리 설정

- 파일 업로드를 위한 MultipartResolver 구현체 라이브러리 등록

 

-> maven repository에서 라이브러리
( commons-fileupload ) 검색 후 아파치 pom 추가

 

2. Bean 등록 + 설정

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"  value="104857600" />
<property name="maxUploadSizePerFile"  value="104857600" />
<property name="maxInMemorySize"  value="104857600" />
</bean>

 

 

/*

maxUploadSize : 한 요청당 허용되는 최대 용량(byte 단위) - 무제한은 -1
maxUploadSizePerFile : 한 파일당 허용되는 최대 용량(byte단위) , 무제한은 -1

maxInMemorySize : 디스크에 저장되지 않고 메모리에 유지하도록 허용하는 바이트 단위
지정된 용량을 초과할 경우 자동으로 파일이 저장된다
메모리가 파일을 기억해놨다가 mULTIPARTrESOLVER 이용해서 DB 수행하고 와도
메모리에 파일이 있음, DB삽입 성공 시 메모리에서 꺼내서 파일로 저장
기본값 : 10240 byte (10KB)
104857600 = 100MB

*/

 

3.  파라미터로 받기

 

List<MultipartFile> "input태그 name"

으로 리스트로 받아낼 수 있다

 

(servers 에서 module 체크해야 서버와 실제 경로가 일치한다)

--> 파일이 업로드 안됐어도 모두 전송되므로 파일 존재 여부를 체크하고 존재하는 파일만 다시 list를 담아야한다

 

--list 새로 생성해서 MutipartResolver에서
 실제 이미지 담겨있는것만 분별+ DB에 필요한 것만 for문으로 추출

 

!imgList.isEmpry()  = true 면 이미지 삽입 [Mybatis 반복삽입진행 ]

 

4. 이미지 리스드 DB 삽입

 

String webPath 

= "/resources/images/board/"; //DB에 저장되는 경로

String reaPath

= session.getServletContext().getRealPath(WebPath); // 실제 물리경로

 

< mapper >

<insert id="insertImgList" parameterType="list">
INSERT INTO BOARD_IMG
SELECT SEQ_IMG_NO.NEXTVAL, A.* FROM 

<foreach collection="list" item="img" 
open="(" close=") A"  separator=" UNION ALL ">
SELECT 

#{img.imgPath} IMG_PATH , 

#{img.imgName} IMG_NM,
#{img.imgOriginal} IMG_ORIGINAL, 

#{img.imgLevel} IMG_LEVEL, 

#{img.boardNo} BOARD_NO 
FROM DUAL
</foreach>


</insert>

 

  <!-- 동적 SQL : 마이바티스의  기능으로 SQL 수행 중 조건, 반복, 특정 구문 추가 등을 동적으로 수행할 수 있음. -->
  <!-- <forEach>  태그 
   - collection : 반복 접근할 컬렉션 형태의 파라미터
   - item : collection에서 반복 시 마다 순차적으로 하나씩 접근한 요소
   - index : 현재 반복 인덱스 
   - open : forEach 시작 전 추가할 구문
   - close : forEach 종료 후 추가할 구문
   - separator : 반복 시 마다 SQL 사이에 추가할 구분자
   -->

 

+ 5. 이미지 업로드시 미리보기 출력 (JS)

	//파일 올라가있는지 check
	const filecheck = [0 , 0 , 0 , 0 , 0];
	
	//이미지 영역 클릭시 파일첨부창 뜨도록
	$(".images").on("click", function(){
		var index = $(".images").index(this);
		if(filecheck[index]==0){
			$("input[name=images]").eq(index).click()
		}
		else{
			if(confirm("이미지를 삭제하시겠습니까?")){
				$(this).children("img").removeAttr("src");
				$(this).children("img").css("display","none");
				$("input[name=images]").eq(index).val("");
				filecheck[index]=0;
			}
		}
	})
	
	//이미지 첨부되면 미리보기 뜨도록
	$("input[name=images]").on("input",function(){
		var index = $("input[name=images]").index(this);
		
		if(this.files[0]){
			console.log("done"+index);
			filecheck[index]=1;
			console.log(filecheck[index]);
			var reader = new FileReader();
			reader.readAsDataURL(this.files[0]);
			reader.onload = function(e){
				$(".images").eq(index).children("img").attr("src", e.target.result);
				$(".images").eq(index).children("img").css("display", "block");
			}
		}
	})

 

 

 

+ Recent posts