IT

JavaScript 만 사용하여 파일에 데이터를 쓸 수 있습니까?

lottoking 2020. 6. 6. 21:11
반응형

JavaScript 만 사용하여 파일에 데이터를 쓸 수 있습니까?


JavaScript를 사용하여 기존 파일에 데이터를 쓰고 싶습니다. 콘솔에서 인쇄하고 싶지 않습니다. 실제로에 데이터를 쓰고 싶습니다 abc.txt. 나는 많은 대답을 읽었지만 콘솔에서 인쇄되는 모든 곳을 읽었습니다. 어떤 곳에서는 코드를 주었지만 작동하지 않습니다. 따라서 실제로 파일에 데이터를 쓰는 방법을 알려주십시오.

코드를 참조했지만 작동하지 않습니다 : 오류 제공 :

 Uncaught TypeError: Illegal constructor 

크롬과

 SecurityError: The operation is insecure.

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을 사용하여 데이터를 파일에 실제로 쓸 수 있습니까? 미리 감사드립니다


이것에 대한 몇 가지 제안-

  1. 클라이언트 시스템에서 파일을 쓰려고하는 경우, 브라우저 간 방식으로 파일을 작성할 수 없습니다. IE에는 "신뢰할 수있는"응용 프로그램이 ActiveX 개체를 사용하여 파일을 읽고 쓸 수 있도록하는 방법이 있습니다.
  2. 서버에 저장하려는 경우 텍스트 데이터를 서버로 전달하고 일부 서버 측 언어를 사용하여 파일 쓰기 코드를 실행하십시오.
  3. 클라이언트 쪽에서 상당히 작은 정보를 저장하기 위해 쿠키를 사용할 수 있습니다.
  4. 로컬 스토리지에 HTML5 API 사용

다음을 사용하여 브라우저에서 파일을 만들 수 있습니다 BlobURL.createObjectURL. 모든 최신 브라우저 에서이 기능을 지원합니다 .

방대한 보안 문제가 발생할 수 있으므로 직접 만든 파일을 저장할 수는 없지만 사용자에게 다운로드 링크로 제공 할 수 있습니다. 다운로드 속성을 지원하는 브라우저에서 링크 download속성통해 파일 이름을 제안 할 수 있습니다 . 다른 다운로드와 마찬가지로 파일을 다운로드하는 사용자는 파일 이름에 대한 최종 결정을 내립니다.

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);

브라우저 자바 스크립트에 대해 이야기하는 경우 보안상의 이유로 로컬 파일에 직접 데이터를 쓸 수 없습니다. 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');


Above answer is useful but, I found code which helps you to download text file directly on button click. In this code you can also change filename as you wish. It's pure javascript function with HTML5. Works for me!

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();
}

In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:

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>


Try

let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();


Use the code by the user @useless-code above (https://stackoverflow.com/a/21016088/327386) to generate the file. If you want to download the file automatically, pass the textFile that was just generated to this function:

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;
}

I found good answers here, but also found a simpler way.

The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)

You can style the link as a button using bootstrap, which is still pure javascript, except for styling.

Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.

This example needs only one button click to create the text-blob and download it:

<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>

참고URL : https://stackoverflow.com/questions/21012580/is-it-possible-to-write-data-to-file-using-only-javascript

반응형