Reputation: 1474
I was wondering whether HTML5 allows one to save/write to a local file within the user's file system. I'm asking this as I know that with HTML5 you can now export data from client and download it as a CSV file for example.
If not with HTML5, what would be the best approach to overwrite the contents, or create a CSV (or any other type of file for that matter) locally from within the client-side script?
Upvotes: 1
Views: 14897
Reputation: 389
I know this is a old question. Test ummahusla' answer it do works, but a small problem with the downloaded file, in my chrome it will download a no name file.
And after some testing here is the working code to download as csv file.
data= 'data:application/csv;charset=utf-8,' + encodeURIComponent(data);
var exportLink = document.createElement('a');
exportLink.setAttribute('href', data);
exportLink.setAttribute('download','test.csv');
exportLink.setAttribute('target','_blank');
exportLink.appendChild(document.createTextNode('test.csv'));
document.getElementById('results').appendChild(exportLink);
Upvotes: 1
Reputation: 2063
Function:
function exportData() {
var data = '';
for (var i=1;i<=2;i++) {
var sep = '';
for (var j=1;j<=4;j++) {
data += sep + document.getElementById(i + '_' + j).value;
sep = ',';
}
data += '\r\n';
}
var exportLink = document.createElement('a');
exportLink.setAttribute('href', 'data:text/csv;base64,' + window.btoa(data));
exportLink.appendChild(document.createTextNode('test.csv'));
document.getElementById('results').appendChild(exportLink);
}
Markup:
<input type="number" id="1_1" value="2">,
<input type="number" id="1_2" value="1">,
<input type="number" id="1_3" value="4">,
<input type="number" id="1_4" value="3">
<br>
<input type="number" id="2_1" value="1">,
<input type="number" id="2_2" value="2">,
<input type="number" id="2_3" value="3">,
<input type="number" id="2_4" value="4">
<br>
<button onclick="exportData()">Export as CSV</button>
<div id="results"></div>
Demo:
Click the button you get a link, click the link and you get a file. Change the values, click the link again and you get a different file. Firefox made me select Excel every time to open it but I don't know whether that's my configuration or a general issue.
Reference:
Is it possible to use any HTML5 fanciness to export local storage to Excel?
Upvotes: 11