코-딩/Javascript

Javascript - blob & UTF-8

ㅋㅂㅋ 2022. 4. 14. 11:34

작성된 html 문서를 다운롣 하는 방법.

1. html을 작성한다.

2. blob으로 형태를 변형한다.

3. 임의로 url을 부여한다.

 

2번 과정에서 간혹 charset=UTF-8로 줘도 먹히지 않고 한글이 깨지는 경우가 존재한다.

 

이럴 경우 작성된 html을 blob에 넣을 때, 앞에 "\ufeff"를 넣어주면 해결된다.

 

예시)

 

let html = "<!DOCTYPE html>"
           + "<head></head>"
           + "<body><div>안녕!</div></body>";

 

let blob = new Blob(["\ufeff" + html], {type: 'text/html; charset=utf-8;'});

 

let url = window.URL.createObjectURL(blob);

 

window.URL.revokeObjectURL(url);