Home  >  Q&A  >  body text

How can I create a file in memory for the user to download instead of going through the server?

<p>Is there a way to create a text file on the client side and prompt the user to download it without any interaction with the server? </p> <p>I know I can't write directly to their computer (security, etc.), but can I create the file and prompt them to save? </p>
P粉231112437P粉231112437444 days ago506

reply all(2)I'll reply

  • P粉473363527

    P粉4733635272023-08-24 17:11:36

    Simple solution for HTML5 browsers...

    function download(filename, text) {
      var element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
      element.setAttribute('download', filename);
    
      element.style.display = 'none';
      document.body.appendChild(element);
    
      element.click();
    
      document.body.removeChild(element);
    }
    form * {
      display: block;
      margin: 10px;
    }
    <form onsubmit="download(this['name'].value, this['text'].value)">
      <input type="text" name="name" value="test.txt">
      <textarea name="text"></textarea>
      <input type="submit" value="Download">
    </form>

    use

    download('test.txt', 'Hello world!');

    reply
    0
  • P粉727531237

    P粉7275312372023-08-24 13:05:14

    You can use data URI. Browser support varies; see Wikipedia. Example:

    <a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>

    Octet stream is used to force download prompts. Otherwise, it may open in the browser.

    For CSV you can use:

    <a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>

    TryjsFiddle Demo.

    reply
    0
  • Cancelreply