Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there any way I can 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 and prompt them to save it?

like image 387
Joseph Silber Avatar asked Sep 08 '10 06:09

Joseph Silber


People also ask

How do I change the name of a file downloaded from my browser?

Click on the "Edit Menu" > Preferences > General tab. Locate the "Save downloaded files to" section, Click on "Downloads" > "Other"... Browse and indicate your new download location.


1 Answers

Simple solution for HTML5 ready 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>

Usage

download('test.txt', 'Hello world!'); 
like image 136
Matěj Pokorný Avatar answered Sep 28 '22 02:09

Matěj Pokorný