Can anybody give some sample code to read and write a file using JavaScript?
This Javascript function presents a complete "Save As" Dialog box to the user who runs this through the browser. The user presses OK and the file is saved.
Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.
// content is the data you'll write to file
// filename is the filename
// what I did is use iFrame as a buffer, fill it up with text
function save_content_to_file(content, filename)
{
var dlg = false;
with(document){
ir=createElement('iframe');
ir.id='ifr';
ir.location='about.blank';
ir.style.display='none';
body.appendChild(ir);
with(getElementById('ifr').contentWindow.document){
open("text/plain", "replace");
charset = "utf-8";
write(content);
close();
document.charset = "utf-8";
dlg = execCommand('SaveAs', false, filename+'.txt');
}
body.removeChild(ir);
}
return dlg;
}
Invoke the function:
save_content_to_file("Hello", "C:\\test");