tika 라이브러리 추가
<dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>2.7.0</version> </dependency>
만약 오류 및 작동이 안될 경우 추가
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
★ inputStream 닫아주도록 한다. 닫지 않으면 오류
/** Tika 라이브러리로 첨부파일 확장자 검사 */
public boolean isPermisionFileMimeType( InputStream inputStream ) {
try {
//final String[] PERMISSION_FILE_MIME_TYPE = {"image/gif", "image/jpeg", "image/png", "image/bmp", "application/pdf", "video/mp4"};
final String[] PERMISSION_FILE_MIME_TYPE = {"image/jpeg", "image/png"};
String mimeType = new Tika().detect(inputStream);
for( int i = 0; i < PERMISSION_FILE_MIME_TYPE.length; i++ ) {
if( PERMISSION_FILE_MIME_TYPE[i].equals(mimeType) ) {
return true;
}
}
return false;
}catch (Exception e){
e.printStackTrace();
return false;
}finally {
try {
inputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import lineage.choco.controller.FileUploadController;
import lineage.choco.model.vo.AttachVO;
import lombok.extern.slf4j.Slf4j;
/**
*
* https://brilliantdevelop.tistory.com/111
*
*/
@Component
@Slf4j
public class AttachUtils {
@Value("${upload.path}")
public String uploadPath;
/** 다중 MultipartFile에서 VO 설정 및 업로드 파일 처리 후 List 리턴
* @throws Exception */
public List<AttachVO> getAttachListByMultiparts(MultipartFile[] boFiles, String boardType, String path)
throws Exception {
List<AttachVO> atchList = new ArrayList<AttachVO>();
for (int i = 0; i < boFiles.length; i++) {
MultipartFile multipart = boFiles[i];
AttachVO vo = this.getAttachByMultipart(multipart,boardType, path);
if (vo != null) {
atchList.add(vo);
}
}
return atchList;
}
/** MultipartFile에서 VO 설정 및 업로드 파일 처리 후 리턴, 없는 경우 null
* @throws Exception */
public AttachVO getAttachByMultipart(MultipartFile multipart, String boardType, String path) throws Exception {
if (!multipart.isEmpty() ) {
//파일 확장자 체크 - 이상 있으면 null 값 반환 처리
InputStream inputStream = multipart.getInputStream();
if(!isPermisionFileMimeType(inputStream)) return null;
AttachVO vo = new AttachVO();
vo.setBoardType(boardType);
vo.setAtchOriginalName(multipart.getOriginalFilename());
vo.setAtchFileSize(multipart.getSize());
vo.setAtchPath(path);
File file = new File(uploadPath + path);
if(!file.isDirectory()) {
file.mkdirs();
}
vo.setAtchFileName(FileUploadController.uploadFile(uploadPath + path, multipart.getOriginalFilename(), multipart.getBytes(), null));
vo.setAtchFancySize(fancySize(multipart.getSize()));
return vo;
} else {
return null;
}
}
private boolean isPermisionFileMimeType( InputStream inputStream ) throws Exception {
//final String[] PERMISSION_FILE_MIME_TYPE = {"image/gif", "image/jpeg", "image/png", "image/bmp", "application/pdf", "video/mp4"};
final String[] PERMISSION_FILE_MIME_TYPE = {"application/zip"};
String mimeType = new Tika().detect(inputStream);
for( int i = 0; i < PERMISSION_FILE_MIME_TYPE.length; i++ ) {
if( PERMISSION_FILE_MIME_TYPE[i].equals(mimeType) ) {
return true;
}
}
return false;
}
private DecimalFormat df = new DecimalFormat("#,###.0");
private String fancySize(long size) {
if (size < 1024) { // 1k 미만
return size + " Bytes";
} else if (size < (1024 * 1024)) { // 1M 미만
return df.format(size / 1024.0) + " KB";
} else if (size < (1024 * 1024 * 1024)) { // 1G 미만
return df.format(size / (1024.0 * 1024.0)) + " MB";
} else {
return df.format(size / (1024.0 * 1024.0 * 1024.0)) + " GB";
}
}
}
js 프론트에서 확장자 체크
$(document).ready(function() {
$("input:file[name='uploadfile']").change(function () {
var str = $(this).val();
var fileName = str.split('\\').pop().toLowerCase();
//alert(fileName);
if(!checkFileName(fileName)){
$(this).val("");
}
});
});
function checkFileName(str){
//1. 확장자 체크
var ext = str.split('.').pop().toLowerCase();
if($.inArray(ext, ['zip']) == -1) {
//alert(ext);
alert(ext+'파일은 업로드 하실 수 없습니다.');
return false;
}
//2. 파일명에 특수문자 체크
var pattern = /[\{\}\/?,;:|*~`!^\+<>@\#$%&\\\=\'\"]/gi;
if(pattern.test(str) ){
//alert("파일명에 허용된 특수문자는 '-', '_', '(', ')', '[', ']', '.' 입니다.");
alert('파일명에 특수문자를 제거해주세요.');
return false;
}
return true;
}
파일 업로드 용량 체크
/* 업로드 체크 */
function fileCheck(e){
// 사이즈체크
const maxSize = 10 * 1024 * 1024 //10MB
let fileSize = 0;
// 브라우저 확인
const browser=navigator.appName;
// 익스플로러일 경우
if (browser=="Microsoft Internet Explorer"){
var oas = new ActiveXObject("Scripting.FileSystemObject");
fileSize = oas.getFile( file.value ).size;
}else{
fileSize = e.files[0].size;
}
if(fileSize > maxSize){
alert("첨부파일 사이즈는 10MB 이내로 등록 가능합니다. ");
$(e).val("");
return;
}
}
적용
<input type="file" name="uploadfile" class="form-control uploadfile" onchange="fileCheck(this)" >














댓글 ( 4)
댓글 남기기