is it possible to create a file on localhost with javascript?
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.
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.
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.
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
<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>
Related
Is it possible to read manifest file contents from Javascript. Requirement is to upload a jar file, read the manifest file content and then display different fields based on manifest file in browser (client side) and then send data to server.
Here is a basic example, tested in chrome.
I've never seen a JAR manifest, but the simplistic code below worked on the demo JAR files i found floating around.
That part is not tricky anyway, ripping open the zip and grabbing the file is, and here's one way:
<html>
<form><input type=file></form>
<script src="http://stuk.github.io/jszip/jszip.js"></script>
<script src="http://stuk.github.io/jszip/jszip-load.js"></script>
<script src="http://stuk.github.io/jszip/jszip-inflate.js"></script>
<script>
function getManifest(e){
var file=e.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var zip = new JSZip(e.target.result);
var manifest = zip.files['META-INF/MANIFEST.MF']
.data
.trim()
.split(/\s*\n+\s*/)
.map(function(a,r){
r=a.split(/\s*:\s*/);
this[r[0]] = r[1];
return this;
},{})[0];
alert(JSON.stringify(manifest, null, "\t"));
};
reader.readAsArrayBuffer(file);
}
document.forms[0].elements[0].onchange=getManifest;
</script>
</html>
of course, you'll want to swap out the file input for a binary ajax call, but it's about impossible to demo such interaction in a paragraph of code like a file input allows...
it's pretty easy, thanks to jszip. about that: see http://stuk.github.io/jszip/ for general info and http://stuk.github.io/jszip/examples/get-binary-files-xhr2.html for a binary ajax demo.
Supposing you talk about Java server app:
No it's not possible.
You need to expose the info from manifest somehow, e.g. through a REST API. See [RestEasy|http://www.jboss.org/resteasy].
And then read it through XmlHttpRequest.
PS: It's not a good idea to expose whatever in META-INF or WEB-INF - it's a security risk.
i am trying to make a file in javascript, but it doesn't be saved in the root.
when the file is made, the sentence i write has to be stored in the file.
or loading a sentence from a textbox is also fine for me.
can anyone give me help??
function createFile() {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var fileObj = fso.CreateTextFile("G:\\soonrok.txt", true);
fileObj.WriteLine("Hello, I am Soonrok!!!");
}
<td>
<input type="button" value="save" onClick="createFile()">
The best you're going to be able to do with JavaScript is create a cookie.
http://www.w3schools.com/js/js_cookies.asp
Or you could do something that only works for IE with ActiveX.
Or see the link from #AurA for Chrome Only tricks and/or ways to download files from a server.
My company has a very strict intranet for work related, the net has a single doorway to allow files in and out. The doorway's security does not allow special kinds of files (*.txt, *.doc etc only), and even in those specific kinds of files, it searches for patterns that approve that the file is really that kind. (You can't simply disguise a *.zip file as a *.doc file.)
As a security project, I was told to find a way to bypass this system, and insert a single C language .exe file that says 'Hello World'.
What I thought was to change the extension to .txt, and base64 encode it so that it would be more acceptable for the system. The problem is, how to decode it once it's in. It's very easy on the outside, PHP or any other decent language can do it for me. However, in there, the only real language I have access to is JavaScript (on IE6 and maybe, MAYBE, on IE8).
So the question is as follows, can I use JavaScript to read a file from the file system, decode it, and write it back? or at least display the result for me?
Note that I don't ask for decoding/encoding a message, this one is easy, I look to decode encode a file.
JSON might be the answer you are looking for. It can actually do the trick.
Encode your txt file in JSON format. It is very likely for it to pass your company's doorway security
var myJsonData = { "text" : "SGVsbG8sIHdvcmxkIQ==" }; // <-- base64 for "Hello, world!"
Import your txt file using plain html script syntax
<script src="hello.txt" type="text/javascript"> </script>
That's it! Now you can access a JSON object using the Syntax:
alert(myJsonData.text);
To complete your job, get this simple Javascript base64 decoder.
You're done. Here's the (very simple) code I've used:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
<script src="base64utils.js" type="text/javascript"> </script>
<script src="hello.txt" type="text/javascript"> </script>
<script type="text/javascript">
function helloFunction() {
document.getElementById("hello").innerHTML = decode64(myJsonData.text);
}
</script>
</head>
<body onload="helloFunction();">
<p id="hello"></p>
</body>
</html>
Using only javascript (i.e. no plugins like AIR etc), browsers don't allow access to the file system. Not only is it not possible to write a file to the disk, it's not possible to even read it - browsers are very strict on that sort of thing, thank goodness.
You cannot do this with straight JS in the browser, security context and the DOM do not allow filesystem access.
You cannot do this with current versions of flash, older versions (pre 7 IIRC) had some security flaws that allowed filesystem access.
You could do this with a custom plugin, and possibly a signed Java applet, or COM (ActiveX component, IE only).
I would suggest working with IT regarding your intranet to open up the context/permissions needed in this case as that may be the shortest path to what you are wanting here. Alternative, you could create a command-line utility to easily encrypt/decrypt given files signed by a common key.
It all depends on how you can get the file in. If you have the base-64 encoded exe as a .txt, you could easily use Flash!
I'm not quite sure how you would implement this, but you can load a file into flash and as3 using flex.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.utils.ByteArray;
//FileReference Class well will use to load data
private var fr:FileReference;
//File types which we want the user to open
private static const FILE_TYPES:Array = [new FileFilter("Text File", "*.txt;*.text")];
//called when the user clicks the load file button
private function onLoadFileClick():void
{
//create the FileReference instance
fr = new FileReference();
//listen for when they select a file
fr.addEventListener(Event.SELECT, onFileSelect);
//listen for when then cancel out of the browse dialog
fr.addEventListener(Event.CANCEL,onCancel);
//open a native browse dialog that filters for text files
fr.browse(FILE_TYPES);
}
/************ Browse Event Handlers **************/
//called when the user selects a file from the browse dialog
private function onFileSelect(e:Event):void
{
//listen for when the file has loaded
fr.addEventListener(Event.COMPLETE, onLoadComplete);
//listen for any errors reading the file
fr.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
//load the content of the file
fr.load();
}
//called when the user cancels out of the browser dialog
private function onCancel(e:Event):void
{
trace("File Browse Canceled");
fr = null;
}
/************ Select Event Handlers **************/
//called when the file has completed loading
private function onLoadComplete(e:Event):void
{
//get the data from the file as a ByteArray
var data:ByteArray = fr.data;
//read the bytes of the file as a string and put it in the
//textarea
outputField.text = data.readUTFBytes(data.bytesAvailable);
//clean up the FileReference instance
fr = null;
}
//called if an error occurs while loading the file contents
private function onLoadError(e:IOErrorEvent):void
{
trace("Error loading file : " + e.text);
}
]]>
</mx:Script>
<mx:Button label="Load Text File" right="10" bottom="10" click="onLoadFileClick()"/>
<mx:TextArea right="10" left="10" top="10" bottom="40" id="outputField"/>
</mx:Application>
To decode it, look into http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/Base64Decoder.html
If the security system scans for patterns in files, it is very unlikely that it will overlook a base64-encoded file or base64-encoded contents in files. E-mail attachments are base64-encoded, and if the system is any good it will scan for potentially harmful e-mail attachments even if they are named .txt. The base64-encoded start of an EXE file is almost certainly recognized by it. So ISTM you are asking the wrong question.
"wget http://www.example.com/file.doc" downloads that file to the local disk.
What is the equivalent of the above in javascript? for example, consider the following html snippet.
<html>
<head>
<script language="JavaScript">
function download_file() {
var url = "http://www.example.com/file.doc"
//
// Question:
//
// what should be done here to download
// the file in the url?
//
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="download_file()">
</body>
</html>
Please suggest a solution that is compliant with all the browsers.
Sangeeth.
After a exploring more than a month, with a help of my friend, we were able to find out the following.
The website where the file is hosted is not allowing us to download the file using window.location = url; or window.open(url);
Finally we had to use the data-downloadurl support from HTML5 as follows
Click here to download the file
We embed this html into the host html and when clicked on the link, it triggers the download.
Why not use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.location = url;
}
See https://developer.mozilla.org/en/DOM/window.location
If you need to open this in a new window/tab first then use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.open(url);
}
See https://developer.mozilla.org/en/DOM/window.open
First thing that always comes in mind of every answerer to this question is executing wget shell command from java script.I'm almost certain that that's not possible because of
major security risk.
You pretty much need to have ajax which sends command to command line
either through php, or another scripting language via ajax...
You could probably make that happen with something like http://www.phantomjs.org/
I am saying probably because I read it from somewhere.
Hiee,
I want to design a frontend of an Uploader page so that
only JPG file can be selected
Max file size should be 1mb
I want to do this check in JavaScript [not in PHP or so ...], can anyone help me ?
[I've no code to show]
Javascript solution i found.
If you want jquery only. convert it to jquery :-)
<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
It's unfriendly to users to insist firmly that filenames must indicate file type, but if you disagree with me you can check the filename on your <input> element. Checking actual file content and size is harder, and will require either Flash or new HTML5 features.
(The file name, stripped of any other path information and possibly even disguised with bogus path information, is available as the <input> element's "value" attribute.)
You may check the extensions (which does not check mime type!)
with something like this:
var el = document.getElementById('filename');
var fileName = el.value;
//do some regex magic to validate for /jpg\z/i
Also: You will also HAVE to check on the server. There's nothing stopping anyone with javascript disabled to upload .exe or other creepy large files.
For the rest I don't think there are many currently backwards compatible solutions for javascript. If you really want to do it client side, you might want to look into flash - since it has more permissions to check it. (Still you need to validate on the server side)
Another solution might be the html5 file api:
http://www.w3.org/TR/FileAPI/#dfn-file
examples with firefox >3.6:
https://developer.mozilla.org/en/using_files_from_web_applications
(Still you need to validate on the server)
i think u can use pluploader for your page.that can be handle your requirement very well.this is the link.http://www.plupload.com/example_queuewidget.php