매번 프로젝트 들어갈때마다 헷갈렸던 파일관련 ...구글링하기 귀찮아서 작성
Controller
1
2
3
4
5
6
7
8
9
10
|
public ResponseEntity<Resource> download(HttpServletRequest request, HttpServletResponse response){
try {
File file = fileUploadService.download(필요한파라미터);
response.setContentType("application/octet-stream; charset=utf-8;"); response.setHeader("Content-Disposition", Utils.getDisposition(file.getName(), Utils.checkBrowser(request))); FileCopyUtils.copy(FileUtils.openInputStream(file), response.getOutputStream());
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
log.error("download error : {}", e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
|
cs |
Service
1
2
3
4
5
6
|
public File download(Long orderId){
//필요한 정보를 찾는다 path, filename등 보통 db에 관리되고 있기때문에 조회한다.
return new File("/test/upload".concat("/"), "test.png");
}
|
cs |
Util class
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
|
public static String checkBrowser(HttpServletRequest request) {
String browser;
String header = request.getHeader("User-Agent");
//신규추가된 indexof : Trident(IE11) 일반 MSIE로는 체크 안됨
if (header.contains("MSIE") || header.contains("Trident")){
browser = "ie";
}
//크롬일 경우
else if (header.contains("Chrome")){
browser = "chrome";
}
//오페라일경우
else if (header.contains("Opera")){
browser = "opera";
}
//사파리일 경우
else if (header.contains("Apple")){
browser = "safari";
} else {
browser = "firefox";
}
return browser;
}
public static String getDisposition(String filename, String browser) throws UnsupportedEncodingException {
String prefix = "attachment;filename=";
String encodedfilename;
if (browser.equals("ie")) {
encodedfilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
}else if (browser.equals("chrome")) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < filename.length(); i++){
char c = filename.charAt(i);
if (c > '~') {
sb.append(URLEncoder.encode("" + c, "UTF-8"));
} else {
sb.append(c);
}
}
encodedfilename = sb.toString();
}else {
encodedfilename = "\"" + new String(filename.getBytes(StandardCharsets.UTF_8), "8859_1") + "\"";
}
return prefix.concat(encodedfilename);
}
|
cs |
파일다운로드에 관해 간단하게 정리했습니다.
나중에 구글링하지말고 이곳에서 보기위해....
'IT > 개발' 카테고리의 다른 글
spring junit void test (0) | 2020.12.01 |
---|---|
spring file delete (0) | 2020.10.29 |
spring 파일 업로드 (0) | 2020.10.27 |
no suitable constructor found for type 에러 분석 (0) | 2020.10.26 |
spring junit test (0) | 2020.10.16 |