파일 첨부 하기

Que Lin·2022년 1월 3일
0

파일 첨부는 파일로 받아와서 - 이름으로 db에 저장하고 - 이름으로 위치를 찾아 파일로 출력되게 한다!

boardDTO에 b_file을 추가한다.
(b_filename은 db에 이미 저장되어 있다.)

private MultipartFile b_file;
private String b_filename;

  • jsp 에서 form으로 전송할 때
    enctype="multipart/form-data"를 꼭 넣어준다.
<form action="/board/save" method="post" enctype="multipart/form-data">
<label for="b_file">파일첨부</label>
 <input class="form-control" type="file" name="b_file" id="b_file">
 <input class="btn btn-outline-success m-3" type="submit" value="글 작성">
</form>

controller

@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(@ModelAttribute BoardDTO board, Model model) throws IllegalStateException, IOException{
		bs.boardSave(board);
		return "redirect:/board/paging";
	}

service - wepapp / resources / 새폴더 생성한 곳에 파일 저장하기

@Override
	public void boardSave(BoardDTO board)throws IllegalStateException, IOException{
		
		br.boardPoint(board.getM_id(),50,"게시물 적립");
		
		MultipartFile b_file = board.getB_file();
		String b_filename = b_file.getOriginalFilename();
		b_filename = System.currentTimeMillis() + "-" + b_filename;
		System.out.println("b_filename: " + b_filename);
		// 파일 저장하기 
		String savePath = "D:\\development_Phl\\source\\spring\\NftGameCommunity\\src\\main\\webapp\\resources\\board_uploadfile\\"+b_filename;
		if(!b_file.isEmpty()) {
			b_file.transferTo(new File(savePath));
		} 
		board.setB_filename(b_filename);
		
		br.save(board);
	}
	

repository && mapper

//repository
public void save(BoardDTO board) {
		sql.insert("Board.boardSave", board);
	}
    
//mapper
<insert id="boardSave" parameterType="board">
insert into board_table(m_id, b_title, b_contents, b_date,b_filename, cate_number)
values(#{m_id},#{b_title},#{b_contents},now(),#{b_filename},#{cate_number})
	</insert>
profile
1일 1커밋 1일 1벨로그!

0개의 댓글