Theme. 파일 업로드 및 다운로드

 

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
package mul.cam.a.controller;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import mul.cam.a.MediaTypeUtiles;
import mul.cam.a.dto.HumanDto;
 
@RestController
public class HelloController {
 
    // file upload
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public String fileUpload(HumanDto human,
                             @RequestParam("uploadFile")
                             MultipartFile uploadFile,
                             HttpServletRequest req) {
        
        System.out.println("HelloController fileUpload " + new Date());
        System.out.println(human.toString());
        
        // 경로
        String path = req.getServletContext().getRealPath("/upload"); // 서버에 업로드
//        String path = "c:\temp"; // 폴더에 upload
        
        
        String filename = uploadFile.getOriginalFilename(); // 기본 파일명
        String filepath = path + "/" + filename;
        
        System.out.println(filepath);
        
        File file = new File(filepath);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(uploadFile.getBytes());
            bos.close();
        
        } catch (Exception e) {
            return "file upload fail";
        } 
        return "file upload success";
        
    }
    
    // file download
    @Autowired
    ServletContext servletContext;
    
    @RequestMapping(value = "/fileDownload")
    public ResponseEntity<InputStreamResource> download(String filename, HttpServletRequest req) throws Exception{
        System.out.println("HelloController download " + new Date());
        
        // 경로
        String path = req.getServletContext().getRealPath("/upload");
        
        MediaType mediaType = MediaTypeUtiles.getMediaTypeForFileName(this.servletContext, filename);
        System.out.println("filename: " + filename);
        System.out.println("mediaType: " + mediaType);
        
        File file = new File(path + "/" + filename); // filename은 업로드됐을 때의 new filename
//        File file = new File(path + File.separator + filename);
        
        InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
        
        // db에서 다운로드 카운트 넣으려면 이 곳에 넣음
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) // file.getName()은 원본 파일명
                .contentType(mediaType)
                .contentLength(file.length())
                .body(isr);
    }
    
    
    
    
}
 
cs

 

이때 사용된 static 메서드는 아래 클래스에 나타내었다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package mul.cam.a;
 
import org.springframework.http.MediaType;
 
import jakarta.servlet.ServletContext;
 
public class MediaTypeUtiles {
 
    public static MediaType getMediaTypeForFileName(ServletContext servletContext, String filename) {
        
        String minType = servletContext.getMimeType(filename);
        
        try {
            MediaType mediaType = MediaType.parseMediaType(minType);
            return mediaType;
        } catch (Exception e) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
        
        
    }
}
 
cs

 

이때, 주의할 것은 프로젝트에 upload 폴더를 추가해줘야 한다는 것이다.

아래와 같이 main 폴더 하위에 webapp 폴더를 생성하고, 그 안에 upload 폴더를 생성해주도록 하자.

 

 

또한, HumanDto 클래스의 경우에는 다음과 같다.

 

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
package mul.cam.a.dto;
 
public class HumanDto {
    
    private int number;
    private String name;
    private String address;
    
    public HumanDto() {}
 
    public HumanDto(int number, String name, String address) {
        super();
        this.number = number;
        this.name = name;
        this.address = address;
    }
 
    public int getNumber() {
        return number;
    }
 
    public void setNumber(int number) {
        this.number = number;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    @Override
    public String toString() {
        return "HumanDto [number=" + number + ", name=" + name + ", address=" + address + "]";
    }
    
    
}
 
cs

 

이제 html 파일을 만들어서 파일 업로드 및 다운로드를 실행해보자. 

abc.txt라는 파일을 업로드 및 다운로드한다. 

 

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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
 
<h3>file upload</h3>
 
<p id="fileResult">...</p>
 
<form id="uploadFileForm">
    number:<input type="text" name="number" value="1002"><br>
    name:<input type="text" name="name" value="성춘향"><br>
    address:<input type="text" name="address" value="남원시"><br><br>    
    
    file:<input type="file" name="uploadFile"><br><br> <!-- controller에서 requestparam 부분 uploadFile과 이름 맞췄다. -->
    
    <button type="button" id="uploadBtn">파일업로드</button>    
</form>
 
<script type="text/javascript">
$(document).ready(function(){
    $("#uploadBtn").click(function(){
        
        $.ajax({
            url:"http://localhost:3000/fileUpload",
            type:"post",
            data:new FormData($("#uploadFileForm")[0]),
            enctype:'multipart/form-data',
            processData:false,
            contentType:false,
            cache:false,
            success:function(str){
                alert('success');
                $("#fileResult").text(str);
            },
            error:function(){
                alert('error');
            }
        });        
    });
});
</script>
 
<br><br>
 
<h3>file download</h3>
 
<button type="button" id="downloadBtn">파일 다운로드</button>
 
<script type="text/javascript">
 
$("#downloadBtn").click(function(){
    
    location.href = "http://localhost:3000/fileDownload?filename=" + "abc.txt";
    
    /* 
    아래 코드는 success는 나오지만, 다운로드는 실행되지 않을 것이다.
    즉, 아래와 같이 다운로드 하면 안된다. 
    
    $.ajax({
        url:"http://localhost:3000/fileDownload",
        type:"get",
        data:{ filename:"abc.txt" },
        success:function(){
            alert('success');    
        },
        error:function(){
            alert('error');
        }        
    });
    */
});
 
</script>
 
</body>
</html>
 
 
 
 
 
 
 
 
 
 
cs

 

 

실행 결과는,

 

 

 

 

 

 

 

 

끝.

 

 

'Spring' 카테고리의 다른 글

[Spring Boot] DB와 연결하기  (0) 2023.03.26
[Spring Boot] 스프링 부트 실행 및 기초  (0) 2023.03.26

+ Recent posts