본문 바로가기
카테고리 없음

javascript 로 텍스트 파일 생성

by DIGITAL2U 2021. 5. 29.

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<title> Text Create & download </title>
</head>
<body>


<script>
//<!CDATA[[

/////////////////////////////////////////////////////
// 텍스트 다운로드 브라우저별 분기
/////////////////////////////////////////////////////

function text_download() {
    var chk = isIE(); // IE(true)
    var date = new Date();

    var fileName = "텍스트_다운로드_" + date.getFullYear() + (date.getMonth()+1) + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + ".txt";
    var content = "제목 : 제목입니다.\n"
        + "-----------------------------------------------------------.\n"
        + "내용 : 동해물과백두산이 마르고 닳도록~.\n"
        + "서명 : " + date.getFullYear() + "년 " + (date.getMonth()+1) + "월 " + date.getDate() + "일  서명: 이대범.\n"
    ;

    if( chk == true ) saveToFile_IE(fileName, content)
    else              saveToFile_Chrome(fileName, content)
    return;
}

/////////////////////////////////////////////////////
// Chrome
// 사용법 : saveToFile_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의 경우
// 사용법 : saveToFile_Chrome(파일명,내용)
/////////////////////////////////////////////////////

function saveToFile_IE(fileName, content) {
    var blob = new Blob([content], { type: "text/plain", endings: "native" });
    window.navigator.msSaveBlob(blob, fileName);
}

/////////////////////////////////////////////////////
// 브라우져 구분
// 사용법 : true(ie) false(not ie)
/////////////////////////////////////////////////////

function isIE() {
    return (navigator.appName === 'Netscape' && navigator.userAgent.search('Trident') !== -1) ||
        navigator.userAgent.toLowerCase().indexOf("msie") !== -1;
}


//]]>

</script>

<button type="button" onClick="text_download()">텍스트다운-스크립트</button>
</body>
</html>