1

is it possible to create a file on localhost with javascript?

1
  • 2
    This 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. Commented Apr 27, 2013 at 14:54

5 Answers 5

7

Not in a webpage. If you're using Windows Script Host then yes you can through ActiveX, but I presume you're not doing that. You can however, send data back to the webserver through AJAX and have it store it for you.

Sign up to request clarification or add additional context in comments.

Comments

3

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

3

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

-1

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

link is broken jet
-2
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.