이미지 DB 넣고 다시 화면에 출력하는 로직
1.jsp
1이미지 업로드 페이지
<form action="" method="" enctype="multipart/form-data">
<input type="file" id="" name="" onchage="readUrl(this)"> <!-- onchage 이벤트를 통해 아래 이미지 출력 -->
<img id="" name="" src="#" alt="your image"/> <!-- 이미지를 보여준다-->
</form>
<!-- 이미지 출력 스크립트 -->
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<script>
2, JSP 화면 출력 페이지
<!-- 이미지 출력 부분 -->
이미지 태그에서 바로 컨트롤러 메소드를 호출할수 있더라 그래서 PrivacyKey 를 이용하여 이미지 파일 호출
<td><img width="50" height="50" src="/showImg/${listBoard.NUM}.do"/></td>
2.java
2.1 DB Insert JavaMethod 생성 (MultipartFile 파일을 이용하여 파일 업로드)
@RequestMapping(value = "/insertBoard.do")
public String insertBoard(ModelMap model,HttpServletRequest request,HttpServletResponse response,MultipartFile imgFile)throws Exception {
String title = request.getParameter("title");
String content = request.getParameter("content");
String imgName = imgFile.getOriginalFilename();
String imgContentType= imgFile.getContentType();
//inputstream 으로 변환
InputStream fis = imgFile.getInputStream();
//IOUtils 이용하여 바이트 배열로 치환
byte[] image = IOUtils.toByteArray(fis);
Map<String,Object> paramMap = new HashMap<String,Object>();
paramMap.put("title", title);
paramMap.put("content",content);
paramMap.put("imgFile", image);
paramMap.put("imgName", imgName);
paramMap.put("imgContentType", imgContentType);
boardService.insertBoard(paramMap);
// 완료 되고 나면 목록 페이지로 url 변경하는 redirect 사용
return "redirect:/listBoard.do";
}
2.2 DB select JavaMethod 생성
@RequestMapping(value = "/showImg/{num}.do")
public void showImg(@PathVariable("num") String num, HttpServletResponse response) throws IOException, SerialException, SQLException {
List<Map<String, Object>> listBoard;
try {
Map<String,Object> paramMap = new HashMap<String,Object>();
paramMap.put("num", num);
listBoard = boardService.selectListBoard(paramMap);
//이미지 파일 이름
response.setHeader("Content-Disposition", "inline;filename=\"" + listBoard.get(0).get("IMGNAME") + "\"");
OutputStream outputStream = response.getOutputStream();
//이미지 contentType
response.setContentType((String) listBoard.get(0).get("IMGCONTENTTYPE"));
// 이미지 바이트 배열
SerialBlob blob = new SerialBlob((byte[]) listBoard.get(0).get("IMGFILE"));
IOUtils.copy(blob.getBinaryStream(), outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
참고 http://xx707xx.tistory.com/47