Skip to content

Instantly share code, notes, and snippets.

@philographer
Created March 20, 2019 09:28
Show Gist options
  • Save philographer/ba5f3c2e6bcb1be2d04e658a7356d1d0 to your computer and use it in GitHub Desktop.
Save philographer/ba5f3c2e6bcb1be2d04e658a7356d1d0 to your computer and use it in GitHub Desktop.
Saving a file with pure JS
<form role="form">
<h3>Saving a file with pure JS!</h3>
<p>Uses HTML5 W3C saveAs() function and the <a href="https://github.com/eligrey/FileSaver.js" target="_blank">FileSaver.js</a> polyfill for this.<br>
I didn't think this was even possible without a server but the docs say it should work in IE 10+, Sweet!</p>
<div class="form-group">
<label for="input-fileName">File name</label>
<input type="text" class="form-control" id="input-fileName" value="textFile" placeholder="Enter file name">
</div>
<div class="form-group">
<label for="textarea">Text</label>
<textarea id="textarea" class="form-control" rows="10" placeholder="Enter text to save">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae iure ab voluptate sunt reiciendis, officia, aliquam temporibus. Quo laudantium quaerat ad, deleniti optio ex, dignissimos, ea accusamus placeat tempora minima!</textarea>
</div>
<button id="btn-save" type="submit" class="btn btn-primary">Save to file</button>
</form>
$("#btn-save").click( function() {
var text = $("#textarea").val();
var filename = $("#input-fileName").val()
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/FileSaver.js"></script>
body {
padding: 1em;
background: #EEE;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment