간단한 게시판을 만드는 미니프로젝트 중 한글명으로 된 파일을 업로드하고나면 SELECT를 할 때 파일을 불러오지 못하는 에러가 있었다.
생각으로는 우리가 주소창에서 종종 보는 것처럼
%2Fmanage%2Fposts%2F (예시, 현재 글쓰기 창 주소에서 가져왔다. 저런 식이라는 거지 저렇게 만든다는 소리가 아님!!)
이런 식으로 암호화 시켜서 저장하면 되지 않을까 싶은데 하는 방법을 모르니 구글의 힘을 빌려보았다.
[Spring] 스프링 파일업로드/ file upload/ 파일업로드 한글깨짐
기본적인 Controller와 jsp 경로 호출 등 셋팅은 되어있다는 가정하에 시작한다. (필자는 STS를 사용 > http://mkil.tistory.com/267 (4)테스트환경 참조~) 1. fileTest.jsp 생성 JSP를 다음과 같이 생성하고 FOR..
mkil.tistory.com
위의 블로그를 참고해서 현재 내가 작성해놓은 파일 업로드 코드에 일부 추가하였음
현재 내가 쓰고있는 파일 업로드 코드는 다음과 같다.
FileManagerService.java
@Component
public class FileManagerService {
public final static String FILE_UPLOAD_PATH = "/Users/jin-yujin/Desktop/yujin/Petpular/workspace/images/";
public String savaFile(String userLoginId, MultipartFile file) {
String directoryName = userLoginId + "_" + System.currentTimeMillis() + "/";
String filePath = FILE_UPLOAD_PATH + directoryName;
// 디렉토리 생성
File directory = new File(filePath);
if (directory.mkdir() == false) {
return null; // 디렉토리 생성 시 실패하면 null을 리턴
}
// 파일 업로드: byte 단위로 업로드한다.
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(filePath + getOriginalFilename()); // getOriginalFilename()는 input에 올린 파일명이다. (한글이면 안됨)
Files.write(path, bytes);
return "/images/" + directoryName + getOriginalFilename();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
주석에 써논 것처럼 한글이면 업로드는 되지만 SELECT를 할 수 없었음...
글에서 참고한대로 파일명을 UUID로 암호화 해서 업로드하니 해결 되었다!
참고 후 작성한 코드는 다음과 같다
FileManagerService.java
@Component
public class FileManagerService {
public final static String FILE_UPLOAD_PATH = "/Users/jin-yujin/Desktop/yujin/Petpular/workspace/images/";
public String savaFile(String userLoginId, MultipartFile file) {
String directoryName = userLoginId + "_" + System.currentTimeMillis() + "/";
String filePath = FILE_UPLOAD_PATH + directoryName;
// 디렉토리 생성
File directory = new File(filePath);
if (directory.mkdir() == false) {
return null; // 디렉토리 생성 시 실패하면 null을 리턴
}
// 파일 업로드: byte 단위로 업로드한다.
try {
byte[] bytes = file.getBytes();
//파일명 암호화
String origName = new String(file.getOriginalFilename().getBytes("8859_1"),"UTF-8");
String ext = origName.substring(origName.lastIndexOf(".")); // 확장자
String saveFileName = getUuid() + ext;
Path path = Paths.get(filePath + saveFileName);
Files.write(path, bytes);
return "/images/" + directoryName + saveFileName;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// uuid 생성
public static String getUuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
수정된 코드를 찬찬히 보자면
String origName = new String(file.getOriginalFilename().getBytes("8859_1"),"UTF-8");
파일명의 한글 깨짐을 방지하기 위해 UTF-8로 바꿔준다.
String ext = origName.substring(origName.lastIndexOf("."));
그리고 확장자만 따로 뽑아내준 다음
String saveFileName = getUuid() + ext;
파일명을 암호화된 uuid + 확장자명으로 바꿔준다. 이렇게 하면 내 파일명이 랜덤하게 암호화된다.
그 후에 저장하고 디렉토리에 파일을 담으면 끝!
'Spring boot' 카테고리의 다른 글
[Spring boot] Ajax로 보낸 JSON 서버에서 받기 (0) | 2022.04.12 |
---|---|
[Spring boot] WebClient 사용해보기 (1) | 2022.04.05 |
[Spring boot] Snake_case to camelCase (0) | 2022.03.22 |
[Spring boot] 의존성 주입(DI) 복습 (0) | 2022.02.23 |
[Spring boot] @RequestParam과 @PathVariable (0) | 2022.01.28 |
간단한 게시판을 만드는 미니프로젝트 중 한글명으로 된 파일을 업로드하고나면 SELECT를 할 때 파일을 불러오지 못하는 에러가 있었다.
생각으로는 우리가 주소창에서 종종 보는 것처럼
%2Fmanage%2Fposts%2F (예시, 현재 글쓰기 창 주소에서 가져왔다. 저런 식이라는 거지 저렇게 만든다는 소리가 아님!!)
이런 식으로 암호화 시켜서 저장하면 되지 않을까 싶은데 하는 방법을 모르니 구글의 힘을 빌려보았다.
[Spring] 스프링 파일업로드/ file upload/ 파일업로드 한글깨짐
기본적인 Controller와 jsp 경로 호출 등 셋팅은 되어있다는 가정하에 시작한다. (필자는 STS를 사용 > http://mkil.tistory.com/267 (4)테스트환경 참조~) 1. fileTest.jsp 생성 JSP를 다음과 같이 생성하고 FOR..
mkil.tistory.com
위의 블로그를 참고해서 현재 내가 작성해놓은 파일 업로드 코드에 일부 추가하였음
현재 내가 쓰고있는 파일 업로드 코드는 다음과 같다.
FileManagerService.java
@Component
public class FileManagerService {
public final static String FILE_UPLOAD_PATH = "/Users/jin-yujin/Desktop/yujin/Petpular/workspace/images/";
public String savaFile(String userLoginId, MultipartFile file) {
String directoryName = userLoginId + "_" + System.currentTimeMillis() + "/";
String filePath = FILE_UPLOAD_PATH + directoryName;
// 디렉토리 생성
File directory = new File(filePath);
if (directory.mkdir() == false) {
return null; // 디렉토리 생성 시 실패하면 null을 리턴
}
// 파일 업로드: byte 단위로 업로드한다.
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(filePath + getOriginalFilename()); // getOriginalFilename()는 input에 올린 파일명이다. (한글이면 안됨)
Files.write(path, bytes);
return "/images/" + directoryName + getOriginalFilename();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
주석에 써논 것처럼 한글이면 업로드는 되지만 SELECT를 할 수 없었음...
글에서 참고한대로 파일명을 UUID로 암호화 해서 업로드하니 해결 되었다!
참고 후 작성한 코드는 다음과 같다
FileManagerService.java
@Component
public class FileManagerService {
public final static String FILE_UPLOAD_PATH = "/Users/jin-yujin/Desktop/yujin/Petpular/workspace/images/";
public String savaFile(String userLoginId, MultipartFile file) {
String directoryName = userLoginId + "_" + System.currentTimeMillis() + "/";
String filePath = FILE_UPLOAD_PATH + directoryName;
// 디렉토리 생성
File directory = new File(filePath);
if (directory.mkdir() == false) {
return null; // 디렉토리 생성 시 실패하면 null을 리턴
}
// 파일 업로드: byte 단위로 업로드한다.
try {
byte[] bytes = file.getBytes();
//파일명 암호화
String origName = new String(file.getOriginalFilename().getBytes("8859_1"),"UTF-8");
String ext = origName.substring(origName.lastIndexOf(".")); // 확장자
String saveFileName = getUuid() + ext;
Path path = Paths.get(filePath + saveFileName);
Files.write(path, bytes);
return "/images/" + directoryName + saveFileName;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// uuid 생성
public static String getUuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
수정된 코드를 찬찬히 보자면
String origName = new String(file.getOriginalFilename().getBytes("8859_1"),"UTF-8");
파일명의 한글 깨짐을 방지하기 위해 UTF-8로 바꿔준다.
String ext = origName.substring(origName.lastIndexOf("."));
그리고 확장자만 따로 뽑아내준 다음
String saveFileName = getUuid() + ext;
파일명을 암호화된 uuid + 확장자명으로 바꿔준다. 이렇게 하면 내 파일명이 랜덤하게 암호화된다.
그 후에 저장하고 디렉토리에 파일을 담으면 끝!
'Spring boot' 카테고리의 다른 글
[Spring boot] Ajax로 보낸 JSON 서버에서 받기 (0) | 2022.04.12 |
---|---|
[Spring boot] WebClient 사용해보기 (1) | 2022.04.05 |
[Spring boot] Snake_case to camelCase (0) | 2022.03.22 |
[Spring boot] 의존성 주입(DI) 복습 (0) | 2022.02.23 |
[Spring boot] @RequestParam과 @PathVariable (0) | 2022.01.28 |