JavaScript만으로 파일에 데이터를 쓸 수 있습니까?
자바스크립트콘솔에 인쇄하고 싶지 않습니다. abc.txt않는 곳에 .코드를 줬지만 작동하지 않는 곳도 있습니다.그러니, 파일에 실제로 데이터를 쓰는 방법을 누가 좀 도와줄 수 있나요?
코드를 참조했지만 작동하지 않습니다. 오류 발생:
수집되지 않은 유형 오류:잘못된 생성자
크롬과
보안 오류:조작이 불안정합니다.
Mozilla에서
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
  var txtFile =new File(afilename);
  txtFile.writeln(output);
  txtFile.close();
}
그럼 실제로 Javascript 또는 NOT만으로 데이터를 파일에 쓸 수 있는 건가요?
및 를 사용하여 브라우저에 파일을 만들 수 있습니다.최신 브라우저는 모두 이 기능을 지원합니다.
작성한 파일을 직접 저장할 수 없습니다.이는 중대한 보안 문제를 일으키기 때문입니다.단, 다운로드 링크로 사용자에게 제공할 수 있습니다.다운로드 속성을 지원하는 브라우저에서 링크 속성을 통해 파일 이름을 제안할 수 있습니다.다른 다운로드와 마찬가지로 파일을 다운로드하는 사용자가 파일 이름에 대한 최종 발언권을 갖게 됩니다.
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});
    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }
    textFile = window.URL.createObjectURL(data);
    // returns a URL you can use as a href
    return textFile;
  };
다음 예시는 이 기술을 사용하여 임의의 텍스트를textarea.
사용자가 링크를 클릭하도록 요구하지 않고 다운로드를 즉시 시작하고 싶다면 Lifecube의 답변처럼 마우스 이벤트를 사용하여 링크를 마우스 클릭으로 시뮬레이션할 수 있습니다.이 기술을 사용한 업데이트된 예를 만들었습니다.
  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');
  create.addEventListener('click', function () {
    var link = document.createElement('a');
    link.setAttribute('download', 'info.txt');
    link.href = makeTextFile(textbox.value);
    document.body.appendChild(link);
    // wait for the link to be added to the document
    window.requestAnimationFrame(function () {
      var event = new MouseEvent('click');
      link.dispatchEvent(event);
      document.body.removeChild(link);
    });
  }, false);
이에 대한 몇 가지 제안 -
- 클라이언트 머신에 파일을 쓰려고 하는 경우는, 크로스 브라우저의 방법으로 쓸 수 없습니다.IE에는 ActiveX 개체를 사용하여 파일을 읽고 쓸 수 있도록 "신뢰할 수 있는" 응용 프로그램이 활성화되는 방법이 있습니다.
- 서버에 저장하려는 경우 텍스트 데이터를 서버에 전달하고 서버 측 언어를 사용하여 파일 쓰기 코드를 실행합니다.
- 클라이언트 측에서 상당히 작은 정보를 저장하려면 쿠키를 선택합니다.
- 로컬 스토리지용 HTML5 API 사용.
브라우저 javascript를 말하는 경우 보안상의 이유로 로컬 파일에 직접 데이터를 쓸 수 없습니다.HTML 5의 새로운 API는 파일 읽기만 허용합니다.
그러나 데이터를 쓰고 사용자가 로컬에 파일로 다운로드할 수 있도록 하려면 다음과 같이 하십시오.다음 코드가 작동합니다.
    function download(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";
    //build download link:
    a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
    if (window.MSBlobBuilder) { // IE10
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */
    if ('download' in a) { //FF20, CH19
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    }; /* end if('download' in a) */
    //do iframe dataURL download: (older W3)
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
}
사용방법:
download('the content of the file', 'filename.txt', 'text/plain');
해라
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();바이너리 데이터를 다운로드하려면 여기를 참조하십시오.
갱신하다
2020.06.14 Chrome을 83.0 이상으로 업그레이드(이유: Sandbox 보안 제한 사항) - 하지만 JSFiddle 버전은 여기서 작동
위의 답변은 유용하지만, 버튼 클릭으로 텍스트 파일을 바로 다운로드 할 수 있는 코드를 찾았습니다.이 코드에서는, 다음과 같이 변경할 수도 있습니다.filename원하시는 대로.HTML5에 의한 순수 자바스크립트 기능. 난 괜찮아! 
function saveTextAsFile()
{
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
      var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }
    downloadLink.click();
}
new를 사용할 수 없는 경우Blob최신 브라우저에서는 최적의 솔루션인 솔루션이지만 파일 크기에 제한이 있는 다음과 같은 간단한 접근방식을 사용할 수 있습니다.
function download() {
                var fileContents=JSON.stringify(jsonObject, null, 2);
                var fileName= "data.json";
                var pp = document.createElement('a');
                pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
                pp.setAttribute('download', fileName);
                pp.click();
            }
            setTimeout(function() {download()}, 500);
$('#download').on("click", function() {
  function download() {
    var jsonObject = {
      "name": "John",
      "age": 31,
      "city": "New York"
    };
    var fileContents = JSON.stringify(jsonObject, null, 2);
    var fileName = "data.json";
    var pp = document.createElement('a');
    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
    pp.setAttribute('download', fileName);
    pp.click();
  }
  setTimeout(function() {
    download()
  }, 500);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile';                     //filename to download
a.click();
여기에서 Blob 문서를 확인하십시오. 파일 형식에 대한 추가 매개 변수를 제공하려면 Blob MDN을 확인하십시오.기본적으로는 .txt 파일이 생성됩니다.
파일을 생성하려면 위의 사용자 @code-code 코드를 사용합니다(https://stackoverflow.com/a/21016088/327386)).파일을 자동으로 다운로드하려면textFile이 함수에 대해 방금 생성되었습니다.
var downloadFile = function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
    iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
}
나는 여기서 좋은 답을 찾았지만, 더 간단한 방법도 찾았다.
blob을 작성하는 버튼과 다운로드 링크를 하나의 링크로 조합할 수 있습니다.링크 요소는 온클릭 속성을 가질 수 있기 때문입니다.(반대가 불가능하다고 생각됩니다만, 버튼에 href 를 추가하는 것은 동작하지 않습니다).
링크를 버튼으로 스타일링할 수 있습니다.bootstrap스타일링을 제외하고 순수 자바스크립트입니다.
또한 버튼과 다운로드 링크를 조합하면 코드를 줄일 수 있습니다.추측한 버튼의 수가 줄어들기 때문입니다.getElementById콜이 필요합니다.
이 예에서는 텍스트블롭을 생성하여 다운로드하기 위해 버튼을 한 번만 클릭하면 됩니다.
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary" 
   onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
   Write To File
</a>
<script>
    // URL pointing to the Blob with the file contents
    var objUrl = null;
    // create the blob with file content, and attach the URL to the downloadlink; 
    // NB: link must have the download attribute
    // this method can go to your library
    function exportFile(fileContent, downloadLinkId) {
        // revoke the old object URL to avoid memory leaks.
        if (objUrl !== null) {
            window.URL.revokeObjectURL(objUrl);
        }
        // create the object that contains the file data and that can be referred to with a URL
        var data = new Blob([fileContent], { type: 'text/plain' });
        objUrl = window.URL.createObjectURL(data);
        // attach the object to the download link (styled as button)
        var downloadLinkButton = document.getElementById(downloadLinkId);
        downloadLinkButton.href = objUrl;
    };
</script>
스크립트 언어의 추가 처리 기능이 필요한 경우 사용하는 로컬 파일버전은 1페이지입니다.
- 아래 코드를 텍스트 파일에 저장
- 파일 확장자를 '.txt'에서 '.html'로 변경합니다.
- 오른쪽 클릭> Open With...> 메모장
- 필요에 따라 워드 프로세싱을 프로그래밍한 후 저장
- 기본 브라우저에서 열려면 html 파일을 두 번 클릭합니다.
- 결과가 검은색 상자에 미리 표시됩니다. 결과 텍스트 파일을 가져오려면 다운로드를 클릭하십시오.
코드:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
    // do text manipulation here
    let string1 = 'test\r\n';
    let string2 = 'export.';
    
    // assemble final string
    const finalText = string1 + string2;
    
    // convert to blob
    const data = new Blob([finalText], {type: 'text/plain'});
    
    // create file link
    const link = document.createElement('a');
    link.innerHTML = 'download';
    link.setAttribute('download', 'data.txt');
    link.href = window.URL.createObjectURL(data);
    document.body.appendChild(link);
    
    // preview the output in a paragraph
    const htmlBreak = string => {
        return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
    }
    const preview = document.createElement('p');
    preview.innerHTML = htmlBreak(finalText);
    preview.style.border = "1px solid black";
    document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>
언급URL : https://stackoverflow.com/questions/21012580/is-it-possible-to-write-data-to-file-using-only-javascript
'programing' 카테고리의 다른 글
| 테이블 잠금과 관련된 트랜잭션 분리 수준 (0) | 2022.10.29 | 
|---|---|
| Composer를 설치하기 위해 PHP의 openssl 확장을 활성화하는 방법은 무엇입니까? (0) | 2022.10.29 | 
| Dropzone.js를 다른 필드와 함께 기존 HTML 형식으로 통합 (0) | 2022.10.29 | 
| MySQL에 이미지를 저장할 수 있습니까? (0) | 2022.10.29 | 
| 'python'을 입력하면 CMD가 Windows Store를 엽니다. (0) | 2022.10.29 |