How to write in txt file with JavaScript - javascript

I want to save something in txt file by using JavaScipt
<input type="date" id="date1">
<script>
var a=document.getElementByid("date1");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("Test.txt", 8, true);
fh.WriteLine("Something");
fh.Close();
</script>
I tried this but it's not working. My main idea is to get value form input and save it in Test.txt

You can't; not reliably, cross-browser. JavaScript in the browser (where you're clearly using it) runs in a sandbox and is not allowed to access the local filesystem. Some older versions of IE will allow you to use the FileSystemObject in the way shown in your question, but only with masses of security warnings, and modern versions don't allow it at all.
The File API and FileSystem API allow limited reading from files in the file system, but writing is still a work in progress.
Your best bet is to post a form to your server, probably with target="_blank", and have the server respond with a Content-Disposition: attachment; filename=Test.txt header and the file data, which will cause the browser to ask the user where to save it.

Related

Migrating to Edge Browser - file upload not working

We are migrating from IE 8 to Edge browser,
Below is the code working in IE 8, to load one file, but not in Edge.
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('filePath').value;
var thefile = fso.getFile(filepath);
Could you please let me know equivalent code for edge browser.
Edge doesn't support ActiveX. You can use File API <input type="file"> to choose files and then use XMLHttpRequest to upload files in modern browsers.
For more information you can refer to this thread and this code sample.
A lot has changed since the code you are trying to upgrade was created. Local Storage now exists and to download a file; (Use case somebody may need to save it for using it locally) a download attrib is added to the anchor html tag. The file needs to be made into a URL-Blob
<a id="download" download="example.png">
<button type="button" onClick="download()" class="UI">Download</button>
</a>
<script>
function download() {
var download = document.getElementById("download");
var image = document.getElementById("meme").toDataURL("image/png").replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
</script>
I would migrate to local-storage or IndexedDB API.
There is no drop in replacement for the activeX. because of security issues.
Major Differences
ActiveX allowed javascript to access a file to read or write, including being able to overwrite itself, anywhere on the hard drive.
HTML5 Allows reading and writting to localdata and several API for data including IndexDB. But file access is limited to what the user specifically uploads or for downloading into the download directory.
A Javascript WIKI page that replaces itself is no longer possible if you want it to overwrite itself. A Javascript WIKI page is possible using the IndexDB. Downloading the content is possible but limited for security reasons.

In JavaScript, are there any security issues associated with FileReader?

Consider the following piece of code:
(Partial) HTML:
<input type="file" accept=".txt" id="theFile" class="button" />
(Partial) JavaScript:
$('#theFile').on('change', function(e){
readFile(this.files[0], function(e) {
var text = e.target.result;
})
})
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsText(file);
}
My question is, is there any security risk involved in the use of FileReader, particularly in this case, when deployed with readAsText? For example, what happens if the file chosen is not a .txt but something else? Is it possible for a malicious user to attack the hosting website in some way?
If it's relevant for the purposes of the question, the full code simply retrieves a text from a .txt file and prints parts of it on screen.
Any other detail or information required, I'd be happy to provide.
Yes, you are fine here there is no security issues.
The code is been executed in the users browser not the server, so even if it was malicious, they would only be infecting themselves.
The code above is only reading the file as text, so even if it was malicious it won't be getting executed.
Were you do need to be careful when creating a website, is if you allow a user to upload malicious files, and then somehow allow them to execute them server side. An example would be were a PHP website didn't have correct security, you allowed them to upload a bad PHP file and this directory was available via the website, the PHP file could then be executed server side by them just putting www.mywebsite.com/upload/danger.php into there browser.

Generate text/xml-file using javascript/jquery?

I would like to know if there is any way to generate a text/xml file in javascript. I want users to be able to fill out a page form when they are offline, save the data, and then use the saved file at a later point in time. The browser will be IE, most likely IE7.
Thanks
The files should be stored on client filesystems, right?
In general, saving data on client's computer by a web script would be considered a security breach. I would avoid doing so but if it's one of your project requirements, you can give it a try.
Since the target platform would be IE, you can try ActiveX. Example code (not tested):
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("c:\\path\\file.txt", true);
fh.WriteLine("Some text");
fh.Close();
You might have to use Flash in order to access the user's filesystem to save the file. That is the way most client-side components work if they need to create a file wholly on the client.
Time to learn ActionScript, and say goodbye to iDevices compatibility!

How do I open a file stream in javascript?

To give a concrete example of what I mean:
Imagine I have an HTML page that looks like this
<div>
<div id="filecontents">
<!-- some html file contents -->
</div>
<input type="button" />
</div>
I would like to be able to click on the button, and it bring me up with a "Open or save file" dialog box.
Is this even possible?
The objective of this is, is for me to be able to open up some html, text, or a CSV using the contents of a div as a data source for the file.
You can do this using the HTML5 FileSystem APIs. A couple tutorials here:
Reading local files in JavaScript
Exploring the FileSystem APIs
Browser support is weak right now, but my guess is that it's the closest to what you want.
doesn't <input type="file" /> do that exact thing?
I don't understand all these answers that say this is not possible without a plugin. I would say it absolutely is possible with standard web technologies, but requires user interaction and server interaction. Of course you can't go reading or writing whatever you want on a user's computer from the web, but you can ask a user for a file (open), and give a user a file (save).
To open a file with JavaScript, use a <input type="file" />. If you want, you can use JavaScript to display the open dialog by calling the click() method on the file input (the DOM method, not the jQuery method). In the onchange handler, submit the form, read the uploaded file, and write the contents to your page.
To save a file with JavaScript, send the contents of the file to the server, prepare the file, and stream it back to the client with a content-disposition header of attachment; filename="file.txt". This header causes the file to be downloaded and saved the user's pc rather than displayed in the browser.
Do that and you've officially written your first cloud computing app!
<input type="file" /> will allow you to upload a file to the server, but you have no direct access to that file, or to the local file system, from javascript - this is a security feature.
If you want to alter the page somehow based on the contents of the file, you will have to do a round-trip: upload the file to the server, then render a new page with the changes you want, and send it back to the client.
I have seen some file-stream-like code written for javascript (i.e., a flash implementation), but they must "load" files via an ajax request and then read the data as a javascript string.
You cannot access the local filesystem from javascript because of security reasons. You can, however, receive files via drag and drop in modern browsers or use an java applet that communicates with your javascript.
EDIT: forgot about the new HTML5 file api linked by Michael Mior. Go with his answer, he's the man. If you need cross browser support, go with the java applet, its painful but works.
Not with pure JavaScript. You can't open a file dialog to save part of the HTML, for example. Even if you could, there is no way to open a local file with JavaScript for security reasons (otherwise, malicious web sites could steal all your data).
But every browser allows to write plugins (most of them are written in JavaScript), so you could try this approach.
Use this script and put it in the button that the file browser should display.
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '"
title = "', escape(theFile.name), '" / > '].join('
');
document.getElementById('list').insertBefore(span, null);
};
})(f); reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

Save XML file on my machine with XMLDom object save()

I'm not able to save to the xml file on my machine.
I have noticed that node value is changed temprorily but not permanent in xml file.
P.S : This is only a simple HTML file with javascript
It is giving me an error "Permission Denied"
function viewBookDetails() {
var xmlDoc = xmlLoader("cart.xml");
//var x = xmlDoc.getElementsByTagName("dogHouse")[0];
var x = xmlDoc.documentElement;
var newel = xmlDoc.createElement("essy");
x.appendChild(newel);
alert(x.xml);
xmlDoc.save("cart.xml");
}
is it not possible to save xml file on my machine?
Thank you,
In general, browser JavaScript has no I/O API and cannot read or write to the client filesystem since that could be a security loophole. I haven't seen or used the save() method before but it looks like it's an IE specific extension to the XML DOM. If you must use it, this thread might provide the solution, the answer that worked for the OP there suggested:
I haven't proofed your code but here is something you might want to try. I am taking a shot in the dark that you are using this on a Windows OS since you are using IE and from the sound of the error. Just take your html file that you have and rename it the whatever.hta and it will then be able to write to the xml file and save.
Also, the documentation for the method says the following for when the argument is a string (as in your code snippet):
String
Specifies the file name. This must be a file name rather than a URL. The file is created, if necessary, and the contents are replaced entirely with the contents of the saved document. This mode is not intended for use from a secure client, such as Microsoft Internet Explorer.
From the forum posts (links below) that deal with the same issue, I gleaned the following:
This is an IE specific extension and so will only work in IE
There are obviously security restrictions in place so you shouldn't be able to do this 'out of the box'
One workaround that crops up often is to rename the file extension to .hta (Hypertext Application) instead of .html
I'm not sure but there might also be some workarounds by changing the permissions for the security zones your application runs in
References:
http://www.codingforums.com/showthread.php?t=25048
http://p2p.wrox.com/xml/4053-error-using-xml-save-method.html
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/204995

Categories