Search code examples
javascriptfileweb-applicationsclient-side

How to create a file in memory for user to download, but not through server?


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?

I know I can't write directly to their machine (security and all), but can I create the file and prompt them to save it?


Solution

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

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

    The octet-stream is to force a download prompt. Otherwise, it will probably 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>
    

    Try the jsFiddle demo.