기록
JAVA Spring 파일 업로드 예제 +미리보기 본문
//요청URL : /lprod/uploadForm
//요청방식 : get
@GetMapping("/uploadForm")
public String uploadForm() {
//forwarding
return "lprod/uploadForm";
}
파일업로드 규칙
1) method는 꼭 post!
2) enctype="multipart/form-data"
3) <input type="file" name=".." name 속성이 반드시 있어야함!
<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script type="text/javascript" src="/resources/js/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(function(){
//이미지 미리보기
let sel_file = [];
$("#input_imgs").on("change",handleImgFileSelect);
$("#input_imgs2").on("change",handleImgFileSelect);
//파라미터 e:onchage 이벤트 객체
function handleImgFileSelect(e){
//이벤트가 발생된 타겟 안에 들어있는 이미지 파일들을 가져옴
let files = e.target.files;
//이미지가 여러개 있을 수 있으므로 이미지들을 분리해서 배열로 만듦
let fileArr = Array.prototype.slice.call(files);
//파일 오브젝트의 배열 반복. f : 배열 안에 들어있는 각각의 이미지 파일 객체
fileArr.forEach(function(f){
//이미지 파일이 아닌 경우 이미지 미리보기 실패 처리(image/jpeg)
if(!f.type.match("image.*")){
alert("이미지 확장자만 가능합니다.");
//함수종료
return;
}
//이미지 객체(f)를 전역 배열타입 변수(sel_file)에 넣자
sel_file.push(f);
//이미지 객체를 읽을 자바스크립트의 reader 객체 생성
let reader = new FileReader();
//e : reader객체가 이미지를 읽는 이벤트
reader.onload = function(e){
//e.target : 이미지 객체
//e.target.result : reader가 이미지를 다 읽은 결과
let img_html = "<p><img src=\""+e.target.result+"\" /></p>";
//객체.append : 누적, .html : 새로고침, innerHTML : J/S
$('.imgs_wrap').append(img_html);
}
reader.readAsDataURL(f);
}); //end for
}
});
</script>
<!--
요청 url : /lprod/uploadFormAction
요청파라미터 : uploadFile이라는 이름의 파일 객체
요청방식 : post
-->
<div class="imgs_wrap"></div>
<form action="/lprod/uploadFormAction" method="post"
enctype="multipart/form-data">
<input type="file" id="input_imgs" name="uploadFile" />
<button type="submit">업로드</button>
</form>
<hr />
<!--
요청 url : /lprod/uploadFormMultiAction
요청파라미터 : uploadFile이라는 이름의 파일 객체
요청방식 : post
-->
<form action="/lprod/uploadFormMultiAction" method="post"
enctype="multipart/form-data">
<input type="file" id="input_imgs2" name="uploadFile" multiple/>
<button type="submit">다중업로드</button>
</form>
연/월/일 폴더 생성
//연/월/일 폴더 생성
public static String getFolder() {
//2023-01-27 형식(format) 지정
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
//2023-01-27
String str = sdf.format(date);
//단순 날짜 문자를 File객체의 폴더타입으로 바꾸기
//\\2023\\01\\27
return str.replace("-", File.separator);
}
업로드
MultipartFile : 스프링에서 제공해주는 타입
* String, getOriginalFileName() : 업로드 되는 파일의 실제 파일명
* boolean, isEmpty() : 파일이 없다면 true
* long, getSize() : 업로드 되는 파일의 크기
* transferTo(File file) : 파일을 저장
// 요청 url : /lprod/uploadFormAction
// 요청파라미터 : uploadFile이라는 이름의 파일 객체
// 요청방식 : post
@PostMapping("/uploadFormAction")
public String uploadFormAction(MultipartFile uploadFile) {
//MultipartFile : 스프링에서 제공해주는 타입
/*
* String, getOriginalFileName() : 업로드 되는 파일의 실제 파일명
* boolean, isEmpty() : 파일이 없다면 true
* long, getSize() : 업로드 되는 파일의 크기
* transferTo(File file) : 파일을 저장
*/
//파일이 저장되는 경로
String uploadFoler = "C:\\upload";
//make folder 시작--------------------
File uploadPath = new File(uploadFoler, getFolder());
log.info("upload Path는 뭘까?"+uploadPath);
//만약 연/월/일 해당 폴더가 없다면 생성
if(uploadPath.exists()==false) {
uploadPath.mkdirs();
}
//make folder 끝----------------------
//파일명
String uploadFileName = uploadFile.getOriginalFilename();
log.info("----------");
log.info("이미지명 : "+uploadFileName);
log.info("파일 크기 : "+uploadFile.getSize());
//--------------------파일명 중복 방지 시작-----------------
//java.util.UUID => 랜덤값을 생성
//ERASDFASDF_개똥이.jpg
UUID uuid = UUID.randomUUID();
uploadFileName = uuid.toString() + "_" + uploadFileName;
//--------------------파일명 중복 방지 끝-----------------
//어디에?무엇을?
//계획을 세움
//C:\\upload\2023\01\27\a11c3600-35f7-4d37-987b-7e6c136323e7_error.jpg
File savaFile = new File(uploadPath,uploadFileName);
//계획실행. 파일 복사됨(클라이언트의 파일을 서버의 공간을 복사)
try {
uploadFile.transferTo(savaFile);
AttachVO attachVO = new AttachVO();
//1) filename : /2023/01/27/ASDFASD_HI.jpg
String filename ="/"+getFolder().replace("\\", "/")+"/"+
uploadFileName;
attachVO.setFilename(filename);
//2) filesize,
Long L = uploadFile.getSize();
attachVO.setFilesize(L.intValue());
//3) thumbnail : /2023/01/27/s_asdfasdf_nullpint.jpg
String thumb = "/"+getFolder().replace("\\", "/")+"/s_"+
uploadFileName;
attachVO.setThumbnail(thumb);
log.info("어태취.."+attachVO);
//이미지 체인지 체킨
try {
//MIME 타입을 가져옴 images/jpeg
String contentType = Files.probeContentType(savaFile.toPath());
log.info("contentType : "+contentType);
//MIME 타입 정보가 images로 시작하는지 여부(TRUE OR FALSE)
if(contentType.startsWith("image")) {//이미지가 맞다면 true
FileOutputStream thumbnail = new FileOutputStream(
new File(uploadPath,"s_"+uploadFileName)
);
//썸내일 생성
Thumbnailator.createThumbnail(uploadFile.getInputStream(),thumbnail,100,100);
thumbnail.close();
}
int result = this.lprodService.uploadFormAction(attachVO);
}catch (Exception e) {
e.printStackTrace();
}
} catch (IllegalStateException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
return "redirect:/lprod/uploadForm";
}
멀티업로드
// 요청 url : /lprod/uploadFormMultiAction
// 요청파라미터 : uploadFile이라는 이름의 파일 객체
// 요청방식 : post
@PostMapping("/uploadFormMultiAction")
public String uploadFormMultiAction(MultipartFile[] uploadFile) {
//파일이 저장되는 경로
String uploadFolder = "c:\\upload";
//make folder 시작--------------------
File uploadPath = new File(uploadFolder, getFolder());
log.info("upload Path는 뭘까?"+uploadPath);
//만약 연/월/일 해당 폴더가 없다면 생성
if(uploadPath.exists()==false) {
uploadPath.mkdirs();
}
//make folder 끝----------------------
for(MultipartFile multipartfile : uploadFile) {
//파일명
String uploadFileName = multipartfile.getOriginalFilename();
log.info("----------");
log.info("이미지명 : "+multipartfile.getOriginalFilename());
log.info("파일 크기 : "+multipartfile.getSize());
log.info("컨텐츠(MIME)타입 : "+multipartfile.getContentType());
log.info("true?:"+multipartfile.isEmpty());
//--------------------파일명 중복 방지 시작-----------------
//java.util.UUID => 랜덤값을 생성
//ERASDFASDF_개똥이.jpg
UUID uuid = UUID.randomUUID();
uploadFileName = uuid.toString() + "_" + uploadFileName;
//--------------------파일명 중복 방지 끝-----------------
//어디에?무엇을?
//계획을 세움
//c:\\upload\\adfasdf_개똥이.jpg
File savaFile = new File(uploadPath,uploadFileName);
//계획실행. 파일 복사됨(클라이언트의 파일을 서버의 공간을 복사)
try {
multipartfile.transferTo(savaFile);
//이미지 체인지 체킨
try {
//MIME 타입을 가져옴 images/jpeg
String contentType = Files.probeContentType(savaFile.toPath());
log.info("contentType : "+contentType);
//MIME 타입 정보가 images로 시작하는지 여부(TRUE OR FALSE)
if(contentType.startsWith("image")) {//이미지가 맞다면 true
FileOutputStream thumbnail = new FileOutputStream(
new File(uploadPath,"s_"+uploadFileName)
);
//썸내일 생성
Thumbnailator.createThumbnail(multipartfile.getInputStream(),thumbnail,100,100);
thumbnail.close();
}
}catch (Exception e) {
e.printStackTrace();
}
} catch (IllegalStateException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
}
return "redirect:/lprod/uploadForm";
}
ServiceImple
@Override
public int uploadFormAction(AttachVO attachVO) {
return this.lprodDao.uploadFormAction(attachVO);
}
DAO
public int uploadFormAction(AttachVO attachVO) {
return this.sqlSessionTemplate.insert("lprod.uploadFormAction",attachVO);
}
Mapper
<!-- 첨부파일 등록 -->
<insert id="uploadFormAction" parameterType="attachVO">
<selectKey resultType="int" order="BEFORE" keyProperty="seq">
SELECT NVL(MAX(SEQ),0)+1 FROM ATTACH
</selectKey>
INSERT INTO ATTACH(SEQ, FILENAME, FILESIZE, THUMBNAIL, REGDATE)
VALUES (
#{seq},
#{filename},
#{filesize},
#{thumbnail},
sysdate
)
</insert>
AttachVO
@Data
public class AttachVO {
private int seq;
private String filename;
private int filesize;
private String thumbnail;
private Date regdate;
}
'JAVA' 카테고리의 다른 글
JAVA sping BOOK 테이블 list 띄우기 (0) | 2023.01.31 |
---|---|
JAVA sping BOOK 테이블 Create (0) | 2023.01.31 |
JAVA Spring 파일업로드 설정 및 업로드하기 (0) | 2023.01.27 |
JAVA Spring tiles 설정 (0) | 2023.01.26 |
JAVA 스프링 root-context.xml 설정 (0) | 2023.01.19 |
Comments