파일업로드

[파일업로드] 업로드한 파일 다운로드 처리

레파캣 2016. 9. 12. 14:48

파일을 업로드 한 뒤에는 이를 다운받을 수 있는 링크를 제공하고 서버에서는 링크를 통한 다운로드 요청에 대해 처리를 해줘야 한다. 클라이언트에서는 아래와 같은 코드를 넣어서 다운로드 링크를 만들 수 있다. <img> 의 src 에 displayFile 이라는 요청을 보내게 설정된 코드이다. 물음표 이후로 파일정보에 대한 query string 이 들어간다.


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
        $.ajax({
            url: '/uploadAjax',
            data: formData,
            dataType: 'text',
            processData: false,
            contentType: false,
            //contentType: 'multipart/form-data',
            type: 'POST',
            success: function(data) {
                console.log(data);
                
                var str = "";
                
                if (checkImageType(data)) {
                    str = "<div><a href='displayFile?fileName=" + getImageLink(data) + "'>"
                            + "<img src='displayFile?fileName=" + data + "' />" 
                            + "</a><small data-src=" + data + ">X</small></div>";
                } else {
                    str = "<div><a href='displayFile?fileName=" + data + "'>" 
                            + getOriginalName(data) 
                            + "</a><small data-src=" + data + ">X</small></div>";
                }
                
                $(".uploadedList").append(str);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
cs




서버에서는 displayFile 이라는 요청에 대해 아래와 같이 handler 를 정의하여 처리를 해준다. 


@ResponseBody 어노테이션을 붙여서 handler 가 리턴하는 값이 HTTP Response Body 에 들어가게 설정한다.

 

실제 응답에는 ResponseEntity 가 들어가는데, HTTP Status 와 사용자 지정 데이터를 넣을수 있게 만들어진 객체이다. 


전송하는 파일의 종류에 따라 Content-Type 을 지정해준다. 이미지는 "image/jpeg" 같은 형식으로, 기타 파일은 "application/octet-stream" 를 넣어준다.


"Content-Disposition" 에는 사용자가 다운로드 받을 때의 보여줄 파일 이름을 넣는다.


전송될 파일은 파일종류에 상관없이 byte[] 형태로 만들어 ResponseEntity 에 넣어준다.


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
    @ResponseBody
    @RequestMapping(value = "/displayFile")
    public ResponseEntity<byte[]> displayFile(String fileName) throws Exception {
 
        InputStream in = null;
        ResponseEntity<byte[]> entity = null;
        
        logger.info("FILE NAME : " + fileName);
        
        try {
            String formatName = fileName.substring(fileName.lastIndexOf("." ) + 1);
            MediaType mType = MediaUtils.getMediaType(formatName);
            
            HttpHeaders headers = new HttpHeaders();
            
            in = new FileInputStream(uploadPath + fileName);
            
            if (mType != null) {
                headers.setContentType(mType);
            } else {
                fileName = fileName.substring(fileName.indexOf("_"+ 1);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.add("Content-Disposition""attatchment; filename=\"" + 
                        new String(fileName.getBytes("UTF-8"), "ISO-8859-1"+ 
                        "\"");
            }
            
            entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
        } catch(Exception e) {
            e.printStackTrace();
            entity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
        } finally {
            in.close();
        }
        
        return entity;
    }
cs