s3 이미지 파일 url을 가져올 때 한글만 오류나는 이유

asaei623·2023년 4월 21일
0

TROUBLESHOOTING

목록 보기
1/1

프론트엔드에서 s3에 이미지 파일을 업로드하고, 업로드한 url을 가져와서 이미지 요소를 바로 렌더했다.

그런데 한글 이름인 경우만 url이 오류가 생겨 렌더가 제대로 되지 않았다.

'cat.jpg' => 'https://s3버킷주소.../cat.jpg'
'고양이.jpg' => 'https://s3버킷주소.../%EA%B3%A0%EC%96%91%EC%9D%B4.jpg'

찾아보니, 파일이름을 받아서 url 주소로 인코딩하는 과정에서 한글을 저런 형식으로 바꾸어 놓는 것이었다.

한글 이름을 그대로 가져오려면, 인코딩된 주소를 utf-8 디코딩을 사용해서 가져와야 한다.

다음과 같은 코드로 한글 이름을 그대로 가져올 수 있다. decodeURIComponent() 함수를 사용하면 된다.

 const filename = "고양이.jpg";

  const encodedFilename = encodeURIComponent(filename);
  console.log(encodedFilename); //%EA%B3%A0%EC%96%91%EC%9D%B4.jpg
  const decodedFilename = decodeURIComponent(encodedFilename);
  console.log(decodedFilename); //고양이.jpg

0개의 댓글