웹에서 스크립트만으로 텍스트 파일을 생성하기 위한 코드를 정리한다. 주로 사용하는 웹브라우져가 IE와 Chrome인데, 텍스트 파일을 생성하는 방식이 서로 다르다. 먼저 크롬의 경우에는 아래와 같다.
function saveToFile_Chrome(fileName, content) {
var blob = new Blob([content], { type: 'text/plain' });
objURL = window.URL.createObjectURL(blob);
// 이전에 생성된 메모리 해제
if (window.__Xr_objURL_forCreatingFile__) {
window.URL.revokeObjectURL(window.__Xr_objURL_forCreatingFile__);
}
window.__Xr_objURL_forCreatingFile__ = objURL;
var a = document.createElement('a');
a.download = fileName;
a.href = objURL;
a.click();
}
다음은 IE에서 작동하는 코드이다.
function saveToFile_IE(fileName, content) {
var blob = new Blob([content], { type: "text/plain", endings: "native" });
window.navigator.msSaveBlob(blob, fileName);
//window.navigator.msSaveOrOpenBlob(blob, fileName);
}
아래는 현재 사용하는 웹브라우저가 IE인지를 식별하는 함수이다.
function isIE() {
return (navigator.appName === 'Netscape' && navigator.userAgent.search('Trident') !== -1) ||
navigator.userAgent.toLowerCase().indexOf("msie") !== -1;
}
