써먹는 웹개발

[Js] 화면 넘김(submit)없이 파일업로드하기 본문

웹개발/Js & Jquery

[Js] 화면 넘김(submit)없이 파일업로드하기

kmhan 2023. 8. 28. 21:07


728x90
반응형

※ 환경은 전자정부 프레임워크 4.16 버전입니다. (poi는 4.1.2버전 사용)

 

1. JSP

1
2
3
4
5
6
                <form id="uploadForm">
                    <input type="text" readonly="readonly" title="File Route" id="excel_file" class="new_com_input" value="회사를 첨부해주세요.">
                    <label>
                        파일선택<input type="file" id="file_off" name="file_off"/>
                    </label>
                </form>
cs

 

2. JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function upload(){
    const form = $('#uploadForm')[0];
    const formData = new FormData(form);
    
    $.ajax({
        url: "/upload.do",
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false
    }).done(function(data){
        ...
    });
}
cs

 

3. JAVA - Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    @SuppressWarnings({ "rawtypes""unchecked" })
    @RequestMapping(method=RequestMethod.POST, value = "/upload.do")
    public ResponseEntity upload(HttpServletRequest request, HttpServletResponse response
            , HttpSession session
            , ModelMap model) throws IOException {
 
        Map<Object,Object> resultMap = new HashMap<Object, Object>();
        List<HashMap<Integer, String>> excelList = null;
        try {
            excelList = researchService.excelUpload(request);
 
            resultMap.put("resultCode""S");
            resultMap.put("resultList", excelList);
        } catch (IllegalStateException e){
            resultMap.put("resultCode""E");
            throw new RuntimeException(e.getMessage(), e);
        }
        
        // 한글 깨짐 방지
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type""application/json; charset=utf-8");
        return new ResponseEntity(resultMap, responseHeaders, HttpStatus.CREATED);
    }
cs

 

4. JAVA - Service

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    @Override
    public List<HashMap<Integer, String>> excelUpload(HttpServletRequest request) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
 
        // 파일 정보 (input type name에서 가져옴)
        CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("file_off");
        
        // 엑셀 정보
        ExcelUtil eu = new ExcelUtil();
        int sheetNum = 0// 1번째 시트 읽음
        int startRowNum = 1// 2번째 줄부터 읽음
        int startCelNum = 0// 1번째 열부터 읽음
        List<HashMap<Integer, String>> excelList = null;
        
        // 테이블 Key 정보
        FactResearchMemVO researchMemVO;
        
        try {
            excelList = eu.excelReadSetValue(file, sheetNum, startRowNum, startCelNum);
            
            if(excelList.size() > 0) {
                int rowNum=1;
                // 엑셀 Row 수 만큼 For문 조회
                for(Object obj: excelList) {
                    Map<Integer, String> mp = (Map<Integer, String>)obj;
                    Set<Integer> keySet = mp.keySet();
                    Iterator<Integer> iterator = keySet.iterator();
                    researchMemVO = new FactResearchMemVO();
 
                    while(iterator.hasNext()) {
                        int key = iterator.next();
                        String value = mp.get(key).toString();
                        
                        switch(key) {
                            case 0:
                               researchMemVO.setCompany(value);
                                break;
                            case 1:
                               researchMemVO.setComCode(value);
                                break;
                            // ...
                        }
                    }
                    
                    if(!"".contentEquals(researchMemVO.getCompany()) && researchMemVO.getCompany() != null) {
                        researchMapper.InsertMember(researchMemVO);
                    }
                }
            }
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            return excelList;
        }
    }
cs
728x90
반응형


Comments