is it possible to create a file on localhost with javascript?
-
2This question is 4 years old and a lot has changed. If you're curious about this now, look into FileWriter, localstorage, indexeddb, requestFileSystem, LocalFileSystem and other options. Still not fully doable in mid 2013, but we're getting there.Matt Greer– Matt Greer2013-04-27 14:54:30 +00:00Commented Apr 27, 2013 at 14:54
5 Answers
You can create cookies to store data on the local machine, which pretty much is the only way to create files on the local machine.
Comments
I assume you have the content of the file ready. Then you can prompt a "save as" dialog like this:
var exportText; // this variable needs to contain your content
var targetFilename = "myfilename.ext"
function presentExportFile() {
var download = document.createElement('a');
// you need to change the contenttype to your needs in the next line.
download.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(exportText));
download.setAttribute('download', targetFilename);
download.style.display = 'none';
document.body.appendChild(download);
download.click();
document.body.removeChild(download);
}
2017 addendum: Since I wrote this, I had one exotic browser (xombrero) reject it. So, I can't say for certain that this is The Way.
Comments
no, this would be a security issue.
You can create a file through a plugin, see https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO
1 Comment
<html>
<head>
<title>Create File</title>
<! This function will create a file named 'newfile' on the same directory as the HTML unless path is given>
<script language="javascript">
function openFile()
{ var filePath = 'c:/filename.txt';
var fileSysObj = new ActiveXObject('Scripting.FileSystemObject');
fileSysObj.CreateTextFile(filePath);
}
</script>
</head>
<body>
This will create a file called "filename.txt" on your c:\ drive.
You must accept the ActiveX control or disable prompting to create a file.
<button type=submit name=button onClick="openFile();">create file</button>
</body>
</html>