[Spring] 파일업로드(Ajax) - 상세처리 2

 - 파일 업로드(ajax) 후  input 태그 내부의 파일 초기화

※ 해당 태그 외부 태그의 빈 값을 통해 초기화

 - 업로드 파일들의 이름 및 썸네일 출력

 - 썸네일 클릭 시 원본 이미지 출력

 - 업로드 파일의 다운로드

 - 업로드 파일 삭제(이미지의 경우 썸네일도 같이 삭제)


사용 JSP 파일
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <!-- 파일 업로드 태그 -->
    <div id='uploadDiv'>
        <input type='file' name='uploadFile' multiple>
    </div>
    
    <!-- 업로드 된 파일 항목 출력 -->
    <div class='uploadResult'>
        <ul>
        </ul>
    </div>
    
    <!-- 썸네일 클릭시 확대 -->
    <div class="bigPictureWrapper">
        <div class="bigPicture">
        </div>
    </div>
    
    <button id='uploadBtn'>upload</button>
</body>
 
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
<script type="text/javascript">
function showUploadFile(result){
    var str = "";
    $.each(result, function(index, obj){
        str +="<li>"+obj.name+"</li>";
    });
    uploadResult.append(str);
    
}
 
function checkExtension(fileName, fileSize){
    if(fileSize >= maxSize){
        alert("파일 사이즈 초과")
        return false;
    }
    
    if(regax.test(fileName)){
        alert("해당 종류의 파일은 업로드할 수 없습니다.")
        return false;
    }
    return true;
}
 
//확대된 원본 이미지 클릭시 해당 이미지 축소 후 원래 화면으로 돌아감
$(".bigPictureWrapper").on("click",function(){
    $(".bigPicture").animate({width:'0%',height:'0%'},1000);
    setTimeout(() =>{$(this).hide();},1000);
});
 
//썸네일 클릭시 해당 원본 이미지 출력
function ShowImage(fileCallPath){
    //alert(fileCallPath);
    $(".bigPictureWrapper").css("display","flex").show();
    $(".bigPicture").html("<img src='/display?filename="+encodeURI(fileCallPath)+"'>").animate({width:'100%', height:'100%'},1000)
    
}
 
 
$(document).ready(function(){
    var regax = new RegExp("(.*?)\.(exe|sh|zip|alz)$");
    var maxSize = 5242880;
    
    // 빈 input 태그에 대해 사전 저장
    // uploadDiv에 대한 태그 값 저작
    var cloneObj = $("#uploadDiv").clone();
    
    //업로드 대상 들에 대한 출력을 위한 태그 지정
    var uploadResult = $(".uploadResult ul");
    
    //on("click", 태그 명, callback 함수)
    //click 시 해당 태그에 대해 callback 함수 수행 
    $(".uploadResult").on("click","span"function(e){
        //해당 class 의 data-file 에 해당하는 값 저장
        //해당 파일의 저장 경로
        var targetFile = $(this).data("file");
        //해당 파일의 데이터 타입 저장
        var type = $(this).data("type");
        console.log(targetFile);
        
        //파일 삭제를 위한 정보를 ajax로 처리
        $.ajax({
            url:'/deleteFile',
            data : {filename : targetFile, type:type},
            dataType : 'text',
            type : 'POST',
            success : function(result){
                alert(result);
            }
        })
    })
    
    //uploadResult class 태그에 항목 추가 수행
    function showUploadedFile(result){
        var str = "";
        $.each(result,function(i, obj){
            //이미지 여부에 대한 항목 출력 처리
            //이미지일 경우 썸네일의 출력
            //이미지가 아닌 경우 더미 이미지 출력
            if(!obj.image){
            //encodeURIComponent : URL 로 데이터를 전달하기 위해서 문자열을 인코딩
            //'&' 등의 특수 기호나 한글 문자에 대한 문자를 이스케이프 문자나 다른 문자가 아닌 '&'나 한글 문자 등의 문자 자체로 볼 수 있게 인코딩
              var fileCallPath =  encodeURIComponent( obj.uploadPath+"/"+ obj.uuid +"_"+obj.filename);
            
              var fileLink = fileCallPath.replace(new RegExp(/\\/g),"/");
              
              //filename : 파일의 원본 이름
              //이미지가 아닌 경우 : 더미 이미지 출력, 해당 파일에 대한 다운로드 및 삭제 기능 추가
              str += "<li><div><a href='/download?filename="+fileCallPath+"'>" 
                      +"<img src='/resources/img/attach.png'>"+obj.filename+"</a>"+
                      "<span data-file=\'"+fileCallPath+"\' data-type='file'>x</span></div></li>" //x 클릭시 해당 파일 삭제
            }else{
              var fileCallPath =  encodeURIComponent( obj.uploadPath+ "/s_"+obj.uuid +"_"+obj.filename);
              
              var originPath = obj.uploadPath+"\\"+obj.uuid+"_"+obj.filename;  
              originPath = originPath.replace(new RegExp(/\\/g),"/");
              
              //이미지인 경우 : 해당 파일에 대한 썸네일 및 실제 파일 보기 및 삭제 기능 추가
              //ShowImage : 썸네일 클릭시 해당 이미지 출력
              str +="<li><a href=\"javascript:ShowImage(\'"+originPath
                      +"\')\"><img src='/display?filename="+fileCallPath+"'></a>"+ // display : json 객체 방식으로 이미지를 받아옴
                              "<span data-file=\'"+fileCallPath+"\' data-type='image'>x</span></li>";          
            }
        });
        uploadResult.append(str);
    }
    
    
    $("#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(!checkExtension(files[i].name, files[i].size)){
                return false;
            }
            
            formData.append("uploadFile", files[i]);
        }
        
        $.ajax({
            url : '/uploadAjaxAction',
            processData : false,
            contentType : false,
            data : formData,
            type : 'POST',
            dataType:'json'// ul 태그 내부의 업로드 항목의 추가를 위해 json 형태로 
            success : function(result){
                alert("uploaded");
                showUploadedFile(result);
                $("#uploadDiv").html(cloneObj.html());//input 태그 초기화
            }
        })
        
    })
    
    
})
</script>
 
</html>
cs


사용 Controller
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package org.zerock.controller;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
 
import net.coobird.thumbnailator.Thumbnailator;
import javax.xml.crypto.Data;
 
 
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.zerock.domain.AttachFileDTO;
 
import lombok.extern.log4j.Log4j;
 
@Controller
@Log4j
public class UploadController {
    private String getFolder() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String str = sdf.format(date);
        return str.replace("-",File.separator);
    }
    
    private boolean checkImageType(File file) {
        try {
            String contentType = Files.probeContentType(file.toPath());
            
            return contentType.startsWith("image");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
 
    @GetMapping("/uploadForm")
    public void uploadForm() {
 
        log.info("upload form");
    }
 
    @PostMapping("/uploadFormAction")
    public void uploadFormPost(MultipartFile[] uploadFile, Model model) {
 
        String uploadFolder = "c:\\upload";
        for (MultipartFile multipartFile : uploadFile) {
 
            log.info("-------------------------------------");
            log.info("Upload File Name: " + multipartFile.getOriginalFilename());
            log.info("Upload File Size: " + multipartFile.getSize());
            
            File saveFile = new File(uploadFolder, multipartFile.getOriginalFilename());
            
            try {
                multipartFile.transferTo(saveFile);
            }catch (Exception e) {
                log.error(e.getMessage());
            }
            
        }
    }
    
    @GetMapping("/uploadAjax")
    public void uploadAjax() {
        
        log.info("upload Ajax");
    }
    
    
    @PostMapping(value = "/uploadAjaxAction", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public ResponseEntity<List<AttachFileDTO>> uploadAjaxPost(MultipartFile[] uploadFile) {
        log.info("uploadAjaxAction....");
        
        List<AttachFileDTO> list = new ArrayList<AttachFileDTO>();
    
        String uploadFolder = "c:\\upload";
        
        String uploadFolderPath = getFolder();
        
        //날짜 별 디렉토리 생성
        File uploadPath = new File(uploadFolder, getFolder());
        log.info("upload path : "+uploadPath);
        if(uploadPath.exists() == false) {
            uploadPath.mkdirs();
        }
        //------------------------------------------------------------------------
        
        for (MultipartFile multipartFile : uploadFile) {
            AttachFileDTO attachDTO = new AttachFileDTO();
            
            String uploadFileName = multipartFile.getOriginalFilename();
            uploadFileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\")+1);
            log.info("only file name : "+uploadFileName);
            attachDTO.setFilename(uploadFileName);
            
            //uuid를 이용한 파일 중복 처리
            UUID uuid = UUID.randomUUID();
            uploadFileName = uuid.toString()+"_"+uploadFileName;
 
            //File saveFile = new File(uploadFolder, uploadFileName);
            try {
                File saveFile = new File(uploadPath, uploadFileName);
                multipartFile.transferTo(saveFile);
                
                attachDTO.setUuid(uuid.toString());
                attachDTO.setUploadPath(uploadFolderPath);
                
                if(checkImageType(saveFile)) {
                    attachDTO.setImage(true);
                    FileOutputStream thumbnail = new FileOutputStream(new File(uploadPath,"s_"+uploadFileName));
                    Thumbnailator.createThumbnail(multipartFile.getInputStream(), thumbnail, 100100);
                    thumbnail.close();
                }
                list.add(attachDTO);
            }catch (Exception e) {
                log.error(e.getMessage());
            }
            
        }
        return new ResponseEntity<List<AttachFileDTO>>(list, HttpStatus.OK);
    }
    
    
    @GetMapping("/display")    
    @ResponseBody
    //이미지를 바이트 배열(byte[])로 값을 가져옴
    public ResponseEntity<byte[]> getFile(String filename) {
 
        log.info("fileName: " + filename);
        
        //해당 이미지의 경로 정보
        //실 파일 경로를 저장하여 file 객체로 생성
        File file = new File("c:\\upload\\" + filename);
 
        log.info("file: " + file);
 
        ResponseEntity<byte[]> result = null;
 
        try {
            HttpHeaders header = new HttpHeaders();
 
            //MIME 타입에 따라 파일의 종류가 달라기기 때문에 헤더에 해당 파일에 대한 타입데이터를 입력
            //probeContentType() : 파일의 MIME 타입을 반환함
            header.add("Content-Type", Files.probeContentType(file.toPath()));
            //FileCopyUtils.copyToByteArray() : 이미지 파일을 바이트 형태로 복사하여 반환 
            result = new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), header, HttpStatus.OK);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    
    @GetMapping(value="/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ResponseBody
    //파일에 대해 byte[] 처리가 가능하나 Resource 를 이용한 방법을 사용
    //@RequestHeader("User-Agent") : 헤더로부터 브라우저에 대한 정보를 얻기 위해 사용
    public ResponseEntity<Resource> downloadFile(@RequestHeader("User-Agent"String userAgent, String filename){
        log.info("download file : "+filename);
        
        //FileSystemResource : 파일 시스템을 기준으로 파일을 검색
        Resource resource = new FileSystemResource("C:\\upload\\"+filename);//파일의 실 경로를 탐색
        
        //대상이 없는 경우 404 페이지 출력
        if(!resource.exists()) {
            log.info(resource);
            return new ResponseEntity<Resource>(HttpStatus.NOT_FOUND);
        }
        
        
        log.info("resource : "+resource);
        
        //대상 파일의 이름만을 추출
        String resourceName = resource.getFilename();
        
        //해당 파일 앞의 uuid 제거
        //실제 다운로드 대상 파일의 이름
        String resourceOriginalName = resourceName.substring(resourceName.indexOf("_")+1);
        
        HttpHeaders headers = new HttpHeaders();
        
        try {
            String downloadName = null;
            
            //각 브라우저 별 다운로드 대상 파일 문자열 깨짐 처리 방지
            if(userAgent.contains("Trident")) {
                log.info("IE browser");
                downloadName = URLEncoder.encode(resourceOriginalName,"UTF-8").replaceAll("\\+"," ");
            }else if(userAgent.contains("Edge")) {
                log.info("Edge browser");
                downloadName = URLEncoder.encode(resourceOriginalName,"UTF-8");
                log.info("Edge name : "+downloadName);
            }else {
                log.info("Chrome browser");
                downloadName = new String(resourceOriginalName.getBytes("UTF-8"),"ISO-8859-1");
            }
            
            //headers.add("Content-Disposition", "attachment; filename="+new String(resourceName.getBytes("UTF-8"),"ISO-8859-1"));
            //Content-Disposition : http response 헤더의 종류
            //attachment : 로컬에 다운로드 및 저장
            //inline : web page 내에서의 표시
            headers.add("Content-Disposition""attachment; filename="+downloadName);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
        
        return new ResponseEntity<Resource>(resource, headers, HttpStatus.OK);
    }
 
    
    @PostMapping("/deleteFile")
    @ResponseBody
    // 파일 이름(저장 파일 경로 포함), 저장 파일의 타입
    public ResponseEntity<String> deleteFile(String filename, String type){
        log.info("deleteFile : "+filename);
        File file;
        try {
        //해당 저장 경로에 대한 절대 경로 저장
        file = new File("c:\\upload\\"+URLDecoder.decode(filename, "UTF-8"));
        //파일 삭제
        file.delete();
        
        //이미지인 경우 썸네일의 삭제도 필요
        if(type.equals("image")) {
            //썸네일은 s_ 문자열을 공통적으로 가짐
            String largeFileName = file.getAbsolutePath().replace("s_""");
            log.info("largeFileName : "+largeFileName);
            file = new File(largeFileName);
            file.delete();
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        
        
        return new ResponseEntity<String>("deleted", HttpStatus.OK);
    }
    
}
 
cs



댓글