IFake
IFake

Reputation:

Create File with Javascript

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

Upvotes: 1

Views: 14750

Answers (5)

Angelo Fuchs
Angelo Fuchs

Reputation: 9941

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.

Upvotes: 3

arijit
arijit

Reputation: 35

<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>

Upvotes: -2

Pierre
Pierre

Reputation: 35226

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

Upvotes: -1

I.devries
I.devries

Reputation: 8916

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.

Upvotes: 3

Ray Hidayat
Ray Hidayat

Reputation: 16249

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.

Upvotes: 7

Related Questions