티스토리 뷰
엑셀 import 기능을 만들면서 첨부파일을 추가했을 때 이 파일을 서버에 저장했다가 읽은 후 파일을 삭제하는 기능을
controller에서 구현하였다.
저장할 디렉토리를 일단 만들어 놓고 그 경로에 첨부된 파일명과 동일하게 파일을 복사했다가 삭제하도록 하였는데,
디렉토리가 있어야 하는 경로에 디렉토리가 있는지 검사하고 없으면 만들어서 그 안에 파일을 복사하도록 수정하였다.
excelUploadPath는 config/properties 파일에 지정해 준 경로이다.
/home/excelUpload 이렇게 주었다면 excelUpload는 디렉토리 이름이다.
destdir을 생성하고 저 디렉토리가 존재하는지 검사한 후 없으면 excelUpload라는 디렉토리를 생성해준다.
destdir.mkdirs() 를 하면 디렉토리가 생성된다.
디렉토리를 생성하고 , destFile의 객체를 생성하는데 excelFile.getOriginalFilename()을 사용하여 첨부된 파일과 동일한 이름으로
파일을 생성한다. 이때의 excelFile은 위에서 request.getFile("excelFile") 을 통해 서버상에 업로드 된 파일에 대한 파일 객체이다.
getFile("excelFile")의 excelFile은 form전송시 첨부파일의 이름이다. <input type="file" name="excelFile"/>
getOriginalFilename()은 업로드한 파일명을 리턴하기 때문에 첨부된 파일과 동일한 이름을 가져오게 된다.
.transferTo() 메소드는 업로드한 파일을 지정한 파일에 저장하는 메소드이다.
excelFile.transferTo(destFile) 로 첨부파일(excelFile)을 생성 되어야 할 경로에 같은 이름으로 지정한 파일(destFile)에 저장한다.
작업이 끝난 뒤에 destFile.delete()를 이용하여 생성한 파일을 삭제한다.
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 | public Map<String, Object> excelUploadAjax(MultipartHttpServletRequest request, HttpSession session) throws Exception{ Map<String, Object> resultMap = new HashMap<String, Object>(); List<User> resultList = new ArrayList<User>(); MultipartFile excelFile =request.getFile("excelFile"); //첨부 된 파일 File destdir = new File(excelUploadPath); //디렉토리 가져오기 if(!destdir.exists()){ destdir.mkdirs(); //디렉토리가 존재하지 않는다면 생성 } File destFile = new File(excelUploadPath+excelFile.getOriginalFilename()); //첨부파일 원래의 이름으로 저장 try{ excelFile.transferTo(destFile); //파일 데이터를 지정한 file(destFile)로 저장 }catch(IllegalStateException | IOException e){ throw new RuntimeException(e.getMessage(),e); } String resultMsg = jClientService.excelUpload(destFile,request); destFile.delete(); //D에 저장된 파일 삭제 resultList = ModuleServiceImpl.getSuccessUserList(); resultMap.put("resultMsg", resultMsg); //결과 메세지 resultMap.put("resultList", resultList); //결과 리스트 return resultMap; | cs |
'업무 > 스프링프로젝트' 카테고리의 다른 글
[JS] 리스트 초기화 / $("#").empty() / 텍스트 비우기 / (0) | 2016.12.05 |
---|---|
[JS] 파일업로드 후 input[type=file] 초기화 / input[type=text] 초기화 (1) | 2016.12.05 |
[mybatis] select / Type / parameterType / resultMap / select문 (0) | 2016.11.22 |
[Spring] jsession 하이재킹 / prevent jsession hijacking / SSL_ID (2) | 2016.11.22 |
[mybatis] 파라미터 바인딩 / Type / update문 (0) | 2016.11.18 |
- Total
- Today
- Yesterday
- 윈도우8.1
- windows 8.1
- 이클립스DB연결
- java
- 스크립팅 요소
- selectbox에 값 매핑
- 체크박스전체선택
- jsp 기초 개념
- 자바스크립트
- jsp
- String[] 파라미터
- Split
- foreach 배열
- 자바
- Hyper-V
- 체크박스전체해제
- Javascript
- SQL
- c 태그
- 스프링
- windows hyper-v
- 게시판페이지설계
- 제이쿼리
- 체크박스
- servlet
- input[type=file]초기화
- input[type=text]초기화
- servlet게시판
- 게시판table설계
- spring
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |