반응형

오늘은 이런 썸네일형 게시판을 만들어 보려고한다. 

삽질을 했지만 이해를 한 것 같아 포스팅을 해본다. 

 

 

일단 부트스트랩을 이용하였다.

 

뷰 부터 보자 

 

        <h1>NEWS AND PRESS RELEASES</h1>
        
        			   <form action="<c:url value='/news/newsList'/>">
                        <div class="search-wrap clearfix">
                            <button type="submit" class="btn btn-primary search-btn" style="margin-right: 24%;">검색</button>
                            <input type="text" name="keyword" class="form-control search-input" value="${pc.paging.keyword}"
                            style="width: 200px; ">
                            <select class="form-control" id="search-select" name="condition" style="width: 80px; margin-left: 54%">
                                <option value="Vboard_title" ${pc.paging.condition == 'vboard_title' ? 'selected' : ''}>제목</option>
                                <option value="Vboard_content" ${pc.paging.condition == 'vboard_content' ? 'selected' : ''}>내용</option>
                                <option value="Vboard_writer" ${pc.paging.condition == 'vboard_writer' ? 'selected' : ''}>작성자</option>
                            </select>
                        </div>
                    </form> 
        
        <div class="row">
         <c:forEach var="vo" items="${newsList}">
          <div class="col">
          <a href="<c:url value='/news/newsDetail?Vboard_no=${vo.vboard_no}'/>">
                <div class="card" style="width: 18rem;">
                <img src="<c:url value='/news/display?fileloca=${vo.fileloca}&filename=${vo.filename}'/>" class="card-img-top" alt="..." style="height: 10rem;">
                <div class="card-body">
                  <h5 class="card-title">Title : ${vo.vboard_title}</h5>
                  <p class="card-text"> Writer : ${vo.vboard_writer}</p>
                  <p class="card-text"> Date : ${vo.vboard_Regdate}</p>
                </div>
                
          </a>

              </div>
          </div>
           </c:forEach>

원래는 테이블로 썻지만 div로 해서 카드뉴스 형식으로 만들어 보았습니다. 

 

모델 객체

 

public class VboardVO {
	
	private int Vboard_no;
	private String Vboard_title;
	private String Vboard_writer;
	private String Vboard_content;
	private int Vboard_hit;
	private int Vboard_like;
	private int Vboard_type;
	private Timestamp Vboard_Regdate;
	private String filename;
	private String fileloca;
	private String filerealname;
	private String uploadpath;
	private String file;
}

 

이렇게 평범한 VO객체를 하나 만들어 준다.

 

여기서 중요한건 파일경로 등등을 설정해준다. 

 

그리고 insert를 해준다. 

 

insert를 해줄때는 반드시 

 

 <form action="<c:url value='/news/newsInsert'/>" method="post" enctype="multipart/form-data">
        <div class="mb-3" style="width: 50%; margin: 0 auto;">
            <label for="exampleFormControlInput1" class="form-label">News Title</label>
            <input type="email" class="form-control" id="exampleFormControlInput1" name="Vboard_title">
          </div>
          <div class="mb-3" style="width: 50%; margin: 0 auto;">
            <label for="exampleFormControlInput1" class="form-label">News Witer</label>
            <input type="email" class="form-control" id="exampleFormControlInput1" name="Vboard_writer">
          </div>
          <div class="mb-3" style="width: 50%; margin: 0 auto;">
            <label for="exampleFormControlTextarea1" class="form-label">News Content</label>
            <textarea class="form-control" id="ckeditor" rows="3" name="Vboard_content"></textarea>
          </div>
          <div class="mb-3" style="width: 50%; margin: 0 auto;">
            <label for="formFileMultiple" class="form-label">썸네일</label>
            <input class="form-control" type="file" id="formFileMultiple" name="file1">
          </div>
 			
 			<input type="hidden" value="0" name="Vboard_type">
          <button type="button" class="btn btn-primary whyBtn">글 작성</button>
          <button type="button" class="btn btn-primary CancleBtn">취 &nbsp; 소</button>
    </form>

enctype="multipart/form-data

으로 데이터를 넘겨줘야 한다. 

 

그 다음 컨트롤러로 넘겨준다. 

 

@PostMapping("/newsInsert")
	public String newsInsert(@RequestParam("file1") MultipartFile file , VboardVO vo , HttpServletRequest req, HttpServletResponse resp) {
		try {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String fileLoca = sdf.format(date);
		
		String uploadPath = req.getSession().getServletContext().getRealPath("/resources/images/thumbnail");
		
		System.out.println();
		File folder = new File(uploadPath);
		if(!folder.exists()) {
			folder.mkdir();
		}
		
		String fileRealName = file.getOriginalFilename();
		
		UUID uuid = UUID.randomUUID();
		String uuids = uuid.toString().replaceAll("-", "");
		
		String fileExtension = fileRealName.substring(fileRealName.indexOf("."), fileRealName.length());
		String fileName = uuids + fileExtension
		
		File saveFile = new File(uploadPath + "\\" + fileName);
	
			file.transferTo(saveFile);
			
			VboardVO Vvo = new VboardVO(0,vo.getVboard_title(),vo.getVboard_writer(), vo.getVboard_content() , 0, 0, vo.getVboard_type(), null, fileName, fileLoca, fileRealName, uploadPath, null);
			
				service.newsInsert(Vvo);

			} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		
		
		//service.newsInsert(vo);
		return "redirect:/news/newsList";
	}

우선 ex) 20220406 이런식으로 파일명을 만들어 주기 위해 심플데이트포멧으로 이름을 생성해주고

데이트 객체를 생성해준다. 

그 뒤 리퀘스트객체를 잉 이용하여 패스를 선언해준다. 

 

폴더를 생성 해 준뒤 

uuid를 생성하여 파일명이 겹치지 않게 설정해준다. 

 

그 뒤  savefile을 이용하여 파일을 uploadpath와 filename으로 저장해준다. 

 

그리고 vo객체를 하나 생성해준다. 

 

그리고 insert를 시켜주면 

 

이런식으로 파일경로나 이름들이 잘 들어오는걸 알 수 있다. 

 

그리고 이제 display 메소드를 만들어 주어야한다. 

 

@GetMapping("/display")
	public ResponseEntity<byte[]> getFile(String fileloca, String filename , HttpServletRequest req, HttpServletResponse resp){
		
		File file = new File(req.getSession().getServletContext().getRealPath("/resources/images/thumbnail"+ "\\" + filename));
		
		ResponseEntity<byte[]> result = null;
		
		try {
		HttpHeaders headers = new HttpHeaders();
	
			headers.add("Content-Type", Files.probeContentType(file.toPath()));
			result = new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), headers, HttpStatus.OK);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
	 
		
		return result;
	}

이렇게 파일 경로를 선언해주면 된다. 

 

 <img src="<c:url value='/news/display?fileloca=${vo.fileloca}&filename=${vo.filename}'/>" class="card-img-top" alt="..." style="height: 10rem;">

이렇게 getMapping으로 진행해주면 끝이 나게 된다. 

 

이렇게 완성하면 끝이 난다. 

 

https://github.com/MoonSeokHyun

반응형

+ Recent posts