Programing

자바 스크립트 : 파일 생성 및 저장

lottogame 2020. 4. 10. 08:05
반응형

자바 스크립트 : 파일 생성 및 저장


파일에 쓰려는 데이터가 있고 사용자가 파일을 저장할 위치를 선택할 수있는 파일 대화 상자를 엽니 다. 모든 브라우저에서 작동한다면 좋을 것이지만 Chrome에서는 작동해야합니다. 나는 이것을 모든 클라이언트 측에서하고 싶다.

기본적 으로이 기능에 무엇을 넣을 지 알고 싶습니다.

saveFile: function(data)
{
}

함수가 데이터를 가져 오는 위치에서 사용자가 파일을 저장할 위치를 선택하고 해당 데이터를 사용하여 해당 위치에 파일을 만듭니다.

도움이된다면 HTML을 사용하는 것도 좋습니다.


trueimage (IE 지원)에서 제안한대로 Awesomeness01 (앵커 태그 필요 없음)에 의해 코드가 약간 개선 되었습니다 .

// Function to download data to a file
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

Chrome, FireFox 및 IE10에서 제대로 작동하는지 테스트했습니다.

Safari에서는 데이터가 새 탭에서 열리 며이 파일을 수동으로 저장해야합니다.


github 의이 프로젝트는 유망합니다.

https://github.com/eligrey/FileSaver.js

FileSaver.js는 기본적으로 지원하지 않는 브라우저에서 W3C saveAs () FileSaver 인터페이스를 구현합니다.

또한 데모를 살펴보십시오.

http://eligrey.com/demos/FileSaver.js/


function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}
<a href="" id="a">click here to download your file</a>
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>

그런 다음 다운로드 속성을 앵커 태그에 넣어 파일을 다운로드합니다.

데이터 URL을 만드는 것보다 내가 이것을 좋아하는 이유는 큰 URL을 만들 필요가 없기 때문에 임시 URL을 생성 할 수 있기 때문입니다.


파일을 작성하기 전에 저장할 위치를 선택할 수 없습니다. 그러나 적어도 Chrome에서는 JavaScript 만 사용하여 파일을 생성 할 수 있습니다. 다음은 CSV 파일을 만드는 오래된 예입니다. 사용자에게 다운로드하라는 메시지가 표시됩니다. 불행히도 이것은 다른 브라우저, 특히 IE에서 잘 작동하지 않습니다.

<!DOCTYPE html>
<html>
<head>
    <title>JS CSV</title>
</head>
<body>
    <button id="b">export to CSV</button>
    <script type="text/javascript">
        function exportToCsv() {
            var myCsv = "Col1,Col2,Col3\nval1,val2,val3";

            window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
        }

        var button = document.getElementById('b');
        button.addEventListener('click', exportToCsv);
    </script>
</body>
</html>

setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')");
function create(text, name, type) {
  var dlbtn = document.getElementById("dlbtn");
  var file = new Blob([text], {type: type});
  dlbtn.href = URL.createObjectURL(file);
  dlbtn.download = name;
}
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>


Chrome과 같은 최신 브라우저의 경우이 자습서에서와 같이 File API를 사용할 수 있습니다 .

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);

이것을 사용하여 파일을 다운로드하고 onclick 속성을 편집하기 만하면됩니다.

function download(text, name, type) {
  var a = document.getElementById("a");
  a.style.display = "block";
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}
#a { display: none; }
<a href="" id="a" download>click here to download your file</a>
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>


콘솔에서 이것을 시도해 보았습니다.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));

자바 스크립트에서는이 작업을 수행 할 수 없습니다. 브라우저에서 실행되는 Javascript에는 보안상의 이유로 아직 충분한 권한이 없습니다 (제안되어 있음).

대신 Downloadify를 사용하는 것이 좋습니다 .

서버 상호 작용없이 텍스트 파일을 만들고 다운로드 할 수있는 작은 자바 스크립트 + Flash 라이브러리입니다.

여기 에서 컨텐츠를 제공하고 저장 / 취소 / 오류 처리 기능을 테스트 할 수있는 간단한 데모를 볼 수 있습니다 .


Chrome과 Firefox의 경우 순수한 JavaScript 방법을 사용하고 있습니다.

(내 응용 프로그램은 Blob.js특수 엔진에서 제공되기 때문에 패키지를 사용할 수 없습니다 : WWWeb 서버가있는 DSP는 아무것도 넣을 공간이 거의 없습니다.)

function FileSave(sourceText, fileIdentity) {
    var workElement = document.createElement("a");
    if ('download' in workElement) {
        workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText);
        workElement.setAttribute("download", fileIdentity);
        document.body.appendChild(workElement);
        var eventMouse = document.createEvent("MouseEvents");
        eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        workElement.dispatchEvent(eventMouse);
        document.body.removeChild(workElement);
    } else throw 'File saving not supported for this browser';
}

메모, 경고 및 족제비 단어 :

  • Linux (Maipo) 및 Windows (7 및 10) 환경에서 실행되는 Chrome 및 Firefox 클라이언트 모두 에서이 코드로 성공했습니다.
  • 그러나 sourceTextMB보다 큰 경우 Chrome은 때때로 오류 표시없이 자체 다운로드에 멈 춥니 다. Firefox는 지금까지이 동작을 나타내지 않았습니다. 원인은 Chrome에서 일부 얼룩 제한 일 수 있습니다. 솔직히, 나는 모른다. 누구든지 수정 (또는 적어도 감지)하는 방법에 대한 아이디어가 있으면 게시하십시오. Chrome 브라우저를 닫을 때 다운로드 이상이 발생하면 다음과 같은 진단이 생성됩니다.크롬 브라우저 진단
  • 이 코드는 Edge 또는 Internet Explorer와 호환되지 않습니다. Opera 나 Safari를 시도하지 않았습니다.

자바 스크립트에는 FileSystem API가 있습니다. 이 기능이 Chrome에서만 작동하도록 처리 할 수있는 경우 http://www.html5rocks.com/en/tutorials/file/filesystem/을 시작하는 것이 좋습니다 .


StreamSaver 는 모든 데이터를 메모리에 보관하지 않고도 대용량 파일을 저장하는 대안입니다.
실제로 파일을 저장할 때 서버 선량을 모방하지만 모든 클라이언트 측을 서비스 워커와 함께 에뮬레이트합니다.

라이터를 가져 와서 수동으로 Uint8Array를 쓰거나 바이너리 readableStream을 쓰기 가능한 스트림으로 파이프 할 수 있습니다

보여주는 몇 가지 예가 있습니다 .

  • 여러 파일을 zip으로 저장하는 방법
  • READStream 을 예를 들어 Response또는 blob.stream()StreamSaver로 파이핑
  • 입력 할 때 쓰기 가능한 스트림에 수동으로 쓰기
  • 또는 비디오 / 오디오 레코딩

가장 간단한 형태의 예는 다음과 같습니다.

const fileStream = streamSaver.createWriteStream('filename.txt')

new Response('StreamSaver is awesome').body
  .pipeTo(fileStream)
  .then(success, error)

Blob을 저장하려면 lobable을 readableStream으로 변환하십시오.

new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference

참고 URL : https://stackoverflow.com/questions/13405129/javascript-create-and-save-file

반응형