smartGeoinfoOriginal/src/main/java/sgis/com/util/FileUploadUtil.java

98 lines
3.4 KiB
Java

package sgis.com.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import egovframework.com.cmm.service.EgovProperties;
import sgis.com.vo.FileUtil;
import sgis.com.vo.FileVO;
import sgis.com.web.BaseController;
/**
* @FileName : FileUploadUtil.java
* @Date : 2025. 7. 15.
* @Creator :
* @Discription :
*/
public class FileUploadUtil extends BaseController {
//logger 설정
private final static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
/**
* 파일 업로드 처리 - 다중
* @param request 파일 Multipart
* @param path uploads/files/yyyy/mm
* @return
*/
public static HashMap<String,Object> multiUploadFormFile(List<MultipartFile> files, String path) {
HashMap<String, Object> result = new HashMap<String, Object>(); // 최종리턴 파일목록(DB INSERT 할 데이타)
// HttpSession session = request.getSession();
MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) files;
Iterator<String> fileNameIterator = mpRequest.getFileNames();
String uploadPath = EgovProperties.getProperty("Globals.File.StoredPath").replaceAll("/", "\\");
String uploadDirPath = "";
if(path.startsWith(System.getProperty("file.separator"))) {
uploadDirPath = path.substring(1).replaceAll("/", "\\");
} else {
uploadDirPath = path.replaceAll("/", "\\");
}
uploadDirPath = uploadPath + uploadDirPath;
String originalFileName = "";
String realFileName = "";
List<FileVO> fileList = new ArrayList<FileVO>();
while (fileNameIterator.hasNext()) {
//파일정보를 하나씩 취득한다
MultipartFile multiFile = mpRequest.getFile((String) fileNameIterator.next());
if (multiFile.getSize() > 0) {
originalFileName = multiFile.getOriginalFilename();
realFileName = FileUtil.getUniqueFileName(uploadDirPath, originalFileName);
File file = new File(uploadDirPath + realFileName);
// 디렉토리가 존재 하지 않을 경우 생성
if(!file.exists()) {
file.setExecutable(false, true);
file.setReadable(true);
file.setWritable(false, true);
file.mkdirs();
}
try{
multiFile.transferTo(file);
FileVO uploadFile = new FileVO();
// 파일 업로드 파일 원본파일명
uploadFile.setFileName(originalFileName);
// 파일 업로드 파일 저장파일명
uploadFile.setStoredFileName(realFileName);
// 파일 업로드 파일 저장경로
uploadFile.setFilePath(uploadDirPath);
// 파일 업로드 파일 크기
uploadFile.setFileSize(multiFile.getSize());
// 파일 업로드 파일 MIME타입
uploadFile.setFileType(multiFile.getContentType());
fileList.add(uploadFile);
} catch (IllegalStateException e) {
logger.error("IllegalStateException");
// 에러메세지리턴
} catch (IOException e) {
logger.error("IOException");
// 에러메세지리턴
}
}
}
result.put("file_list", fileList);
return result;
}
}