Save Div Contents as a file and Load Div Contents from file?

Forums jQuerySave Div Contents as a file and Load Div Contents from file?
Staff asked 3 months ago

Is it possible to save the contents inside of a Div as a file (Could be .txt or .html or anything) and loading the contents from the file later on (Replacing the content already in the DIV). If this can’t be done via JS/Jquery, would it be possible in a diff language (php?).

For example:

<div class="etc">
    Content here
</div>
        
<a href='link.html' download>
    <button>Save Content</button>
</a>

<button>Load Content</button>

 

Answers (1)

Add Answer
Prince Dhameliya Marked As Accepted
Staff answered 3 months ago

In fact, I had some outdated code lying around that accomplished this. This is a very simple example from which you might extrapolate. HTML5 is necessary, though. It might also be greatly improved (old code, throws up)

Another option would be to use Jquery.ajax to post contents and create the file on your backend (using php), which would enable you to create more complex file formats than just raw text with a file extension.

<html>
  <head>
    <title>Basic File In/Out</title>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <script>
      function checkFileAPI() { //check if api is supported (req HTML5)
        if (window.File && window.FileReader && window.FileList && window.Blob) {
          return true;
        }else{
          alert('The File APIs are not fully supported by your browser. Use a better browser.');
          return false;
        };
      };

      $(document).ready(function() {
        checkFileAPI();

        $("#fileInput").change(function(){
          if(this.files && this.files[0]) {
            reader = new FileReader();
            reader.onload = function (e) {
              // do parsing here. e.target.result is file contents
              $("#contents").html(e.target.result);
            };
            reader.readAsText(this.files[0]);
          };
        });

        $("#downloadInput").click(function(){
          var element = document.createElement('a');
          filecontents = $('#contents').html();
          // do scrubbing here
          //

          element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(filecontents));
          element.setAttribute('download', 'output.html');

          element.style.display = 'none';
          document.body.appendChild(element);

          element.click();

          document.body.removeChild(element);
        });
      });
    </script>

  </head>

  <body>
    <div id="contents">
      Content here
    </div>

    <input type="file" id="fileInput" class="btn">
    <button type="button" id="downloadInput" class="btn">Download</button>
  </body>

</html>

 

Subscribe

Select Categories