일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- log4jdbc
- 게시판만들기
- service
- update
- 게시판 List
- MVC
- 게시판
- hikaricp
- delete
- CRUD
- 환경설정
- 서비스계층
- Oracle 연결
- mybatis
- Controller
- Oracle
- MVC CRUD
- log4j
- jdbc
- MVC설정
- spring
- MVC 게시판
- Connection pool
- Today
- Total
yahayaha
26. ajax 파일 업로드 (파일 확장자, 크기 처리, 년/월/일 폴더 처리, UUID 중복 파일 처리) 본문
커뮤니티나 포털에서 특정 확장자를 제외한 파일의 업로드를 제한하는 경우가 많음.
이유는 파일업로드 취약점을 이용한 웹셀 공격을 조치하기 위함.
일단 exe, sh, zip 확장자와 특정 크기 이상의 파일은 업로드할 수 없도록 javascript로 처리 예정. 파일 확장자의 경우
정규식을 이용해서 검사를 실행.
먼저 uploadAjax.jsp에 javascript 코드 추가.
$(document).ready(function(){
var regex = new RegExp("(.*?)\.(exe|sh|zip|alz)$");
var maxSize = 5242880; //5MB
function checkExtenstion(fileName, fileSize){
if(fileSize >= maxSize){
alert("파일 사이즈 초과");
return false;
}
if(regex.test(fileName)){
alert("해당 종류의 파일은 업로드할 수 없습니다.");
return false;
}
return true;
}
$("#uploadBtn").on("click", function(e){
var formData = new FormData();
var inputFile = $("input[name='uploadFile']");
var files = inputFile[0].files;
console.log(files);
for(var i = 0; i < files.length; i++){
if(!checkExtenstion(files[i].name, files[i].size)){
return false;
}
formData.append("uploadFile", files[i]);
}
$.ajax({
url: '/uploadAjaxAction',
processData: false,
contentType: false,
data: formData,
type: 'POST',
success: function(result){
alert("Upload");
}
}); //$.ajax
});
});
첨부파일을 업로드하면 for 루프에서 checkExtenstion()을 호출해서 확장자와 파일의 크기를 체크함.
중복 이름 첨부파일 처리
첨부파일을 저장할 때 생각해야하는 두 가지가 있음.
1. 중복된 이름의 파일처리
2. 판 폴더 내에 너무 많은 파일의 생성.
1번의 경우는 UUID를 이용해서 중복이 발생할 가능성이 거의 없는 문자열을 생성해서 처리.
2번의 경우에는 하나의 폴더에 생성될 수 있는 파일의 개수에 대한 문제인데, 한 폴더에 너무 많은 파일이 있는 경우 속도의 저하와 개수의 제한 문제가 생길 수 있음. 이를 해결하는 일반적인 방법으로 년/월/일 단위의 폴더를 생성해서 저장.
우선 년 / 월 / 일 처리를 먼저 진행.
java.io.File에 존재하는 mkdirs()를 이용하면 필요한 상위 폴더까지 한 번에 생성할 수 있음.
Java API에서 제공하는 File.mkdir()와 File.mkdirs() 두 개의 API를 제공하는데
두 가지 모두 디렉토리를 생성하는 기능을 하지만 차이점이 있음.
File.Mkdi() | File.mkdirs() |
만들고자 하는 디렉토리의 상위 디렉토리가 있을 경우 생성 불가 | 만들고자 하는 디렉토리의 상위 디렉토리가 존재하지 않을 경우 상위 디렉토리까지 생성. |
Controller에 추가 메서드와 수정을 진행.
private String getForlder() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String str = sdf.format(date);
return str.replace("-", File.separator);
}
@PostMapping("/uploadAjaxAction")
public void uploadAjaxPost(MultipartFile[] uploadFile) {
log.info("update ajax post...");
String uploadFolder = "C:\\upload";
//폴더 만드는 부분 -------
File uploadPath = new File(uploadFolder, getForlder());
log.info("업로드 경로 : " + uploadPath);
if(uploadPath.exists() == false) {
uploadPath.mkdirs();
}
// 년 월 일 폴더만들기
for(MultipartFile multipartFile : uploadFile) {
log.info("-------------");
log.info("Upload File Name : " + multipartFile.getOriginalFilename());
log.info("Upload File Name : " + multipartFile.getSize());
String uploadFileName = multipartFile.getOriginalFilename();
//인터넷 익스플로러 파일 경로
uploadFileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\") + 1);
log.info("only file name : " + uploadFileName);
File saveFile = new File(uploadPath, uploadFileName);
try {
multipartFile.transferTo(saveFile);
} catch (Exception e) {
log.error(e.getMessage());
}
}
} // end uploadAjaxAction
getFolder()는 오늘 날짜의 경로를 문자열로 생성. 생성된 경로는 폴더 경로로 수정한 뒤 반환.
uploadAjaxPost()에서 해당 경로가 있는지 검사하고 폴더를 생성. 그리고 다시 이미지를 저장해보면 폴더가 생성되는걸 확인 가능함.
중복 방지 UUID
파일 이름을 생성할 때 동일한 이름으로 업로드되면 기존 파일이 지워지기에 UUID의 값을 이용해서 처리.
@PostMapping("/uploadAjaxAction")
public void uploadAjaxPost(MultipartFile[] uploadFile) {
log.info("update ajax post...");
String uploadFolder = "C:\\upload";
//폴더 만드는 부분 -------
File uploadPath = new File(uploadFolder, getForlder());
log.info("업로드 경로 : " + uploadPath);
if(uploadPath.exists() == false) {
uploadPath.mkdirs();
}
// 년 월 일 폴더만들기
for(MultipartFile multipartFile : uploadFile) {
log.info("-------------");
log.info("Upload File Name : " + multipartFile.getOriginalFilename());
log.info("Upload File Name : " + multipartFile.getSize());
String uploadFileName = multipartFile.getOriginalFilename();
//인터넷 익스플로러 파일 경로
uploadFileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\") + 1);
log.info("only file name : " + uploadFileName);
//중복 방지 UUID
UUID uuid = UUID.randomUUID();
//파일 이름에 하이픈 추가해서 중복 파일 이름 방지.
uploadFileName = uuid.toString() + "_" + uploadFileName;
//년 월 일에 생성된 파일저장.
File saveFile = new File(uploadPath, uploadFileName);
try {
multipartFile.transferTo(saveFile);
} catch (Exception e) {
log.error(e.getMessage());
}
}
} // end uploadAjaxAction
randomUUID()를 이용해서 임의의 값을 생성. 생성된 값은 원래 파일 이름과 구분할 수 있도록 중간에 " _ "를 추가.
'spring > 프로젝트' 카테고리의 다른 글
27-2. 파일 업로드(썸네일 이미지) (2) | 2024.02.18 |
---|---|
27-1. 파일 업로드(썸네일 이미지) (0) | 2024.02.17 |
25. ajax 파일 업로드 (0) | 2024.02.14 |
24. 댓글 페이징처리. (0) | 2024.02.12 |
23. 댓글 기능( 이벤트 , view 처리) (2) | 2024.02.11 |