1

I have a form on my website that creates output for the user based on the input. I want to create a text file with this output for the user to download (with browser download prompt, no security problems).

Is there a way to do this with Javascript/jQuery without using PHP to create the file on the server first?

Can I use some kind of Javascript object to serve as a dummy-file so that the user can download it (to solve the problem that there isn't a real txt file for the user to download from the server)?

2

1 Answer 1

3

You can achieve that by using Blob (browser support, polyfill). Check out this example by @UselessCode:

(function () {
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);

    return textFile;
  };


  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');

  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>

Sign up to request clarification or add additional context in comments.

1 Comment

There's a Blob polyfill for browsers that don't support it: github.com/eligrey/Blob.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.