Is there a JavaScript library that allows to save strings as txt files, and works cross-browser?
In the past, I have been using Downloadify, but I am looking at another option for a couple reasons:
I hope to find a pure JavaScript solution, without the need for Flash
it seems that Downloadify is not updated anymore
(no update in the past 18 months)
I am experiencing an issue with Downloadify in IE 9, where strings are cut off
Here is what you need. But it's not cross-browser yet. Works in Google Chrome.
<a download="MyFile.txt"
href="your-data-uri-here"
draggable="true"
class="dragout"
>Download ready</a>
Also Wikipedia has a good article about Data URI
As far as I know, the only way is to use data: URLs to force a download:
var data = "This is a test";
window.location.href = "data:application/x-download;charset=utf-8," + encodeURIComponent(data);
Two catches here:
It won't work in MSIE because its support of data: URLs is very limited (supposedly for security reasons). So you will still need Downloadify there.
You cannot specify a file name, the suggested file name will depend on the browser used. And file type will be "unknown" (you cannot use a known MIME type because the browser won't offer to download the file then).
Bonus reading: there was a W3.org discussion in February 2010 on fixing the second problem: http://lists.w3.org/Archives/Public/uri/2010Feb/thread.html#msg58. However, this doesn't seem to have made it into any specification so far, let alone browser implementations.
FileSaver API is cross-browser compatible
var text = "Hello, world!";
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "filename.txt");
Related
I have the following problem:
We are currently using a script to export data from CAD assemblies. This script is running in the Creo browser, which is currently IE. To access the correct directory the following code is used:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.CreateTextFile(session.GetCurrentDirectory() + ComponentName + ".xml", true);
f.Write(iht.join("\n"));
f.Close();
The Creo bowser is going to be switched to Chrome. Because of this ActiveX is no longer going to work. Is there a way to archive the same result with different code in Chrome?
Creo is not supporting Chrome Plugins, so IE Tab is not an option.
Any help is greatly appreciated!!
There is a non-standard feature:
https://developer.mozilla.org/en-US/docs/Web/API/FileSystem
But again, it is non-standard.
Edit: as written in that link, "This interface will not grant you access to the users filesystem. Instead you will have a "virtual drive" within the browser sandbox."
No. No more ActiveX.
In the past, most (auto)CAD programs came with a builtin LISP editor you could write scripts in. Maybe that is usable to rewrite the export if you find a LISP programmer.
Myself, I would install node.js on a server so you can use their file system module, which is a good replacement for the old active x object. This probably will require you to copy the files to that server though, so your current workflow might change a bit.
I've got a web page which needs to be able to load files into the DOM from the local machine on which the browser is running. I've found that this is very easy to do using the HTML 5 File API.
I can just do:
var reader = new FileReader();
reader.onload = function (fileContents) { ... load contents to a div ... }
reader.readAsText(f) //where f is an HTML5 File object
Annoyingly, I need this to work in IE7, and also some earlier versions of Firefox which don't support the API. Is there any easy way to load a local file into the DOM in older browsers?
Many thanks!
No, you cannot do that in older browsers. FileReader (any file system access really) is a new HTML5 feature which is not supported in older browsers.
Your best option in an older browser is either:
A Silverlight, Flash or Java app (or similar) that runs on the client-side and has local file system access.
Having the user upload files using the <input type="file"> element, and do your processing server-side.
Further to the other answers here, it does appear that there's no consistent way of doing this client-side (other than Flash) for older browsers.
For IE7/8 however, I've managed to hack something together using ActiveX.
var filePath = f:\oo.txt;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var textStream = fso.OpenTextFile(filePath);
var fileData = file.ReadAll();
I can then pass this to the same function as reader.onload in the question above. Obviously this is a bad, hacky solution, and liable to be blocked by some security policies - it does at least work for IE7 though!
Looks like you can do that through Flash. Flash alternative for FileReader HTML 5 API
While developing a pattern generator I am running into the same problem described in this question from 2011.
The answers given don't really offer a cross-browser, client-side solution.
I would accept any of the following solutions when clicking the Export Pattern button:
Triggering a download through canvas2image while ensuring that the file is saved with a .png extension (no matter what the filename is set to) or,
Display a widget (KendoUI preferably) with the image resulting from the Canvas2Image.saveAsPNG() method and let the user save it from there preferably not using the lame right-click solution, but with a link or a button.
HTML for the button I'm currently using:
<button id="downloadbtn" onClick="javascript:downloadImage()" data-role="button" class="k-button">Export Pattern</button>
Function that triggers the download:
function downloadImage () {
//...extra code omitted
var oCanvas = document.getElementById("my_canvas");
oCanvas.width = $("#pixels-h").val();
oCanvas.height = $("#pixels-v").val();
Canvas2Image.saveAsPNG(oCanvas);
//...extra code omitted
}
The file seems to download fine under OSX with Chrome Version 23.0.1271.95 and Safari Version 5.1.7 (6534.57.2).
I have a report of someone unable to open the file after downloading it under Firefox 17.0.1 for OSX. Apparently the download generates a .part file.
The biggest issue is that without a file extension I doubt that this method can be reliable.
I am looking for a client-side only solution with the widest possible compatibility with current browsers, so I guess the HTML5 download attribute would not do the trick as it is currently only supported in Chrome.
Any creative solutions?
I ran into the same issue. The basic problem is the filename needs to be added in the header but canvas2images uses document.location.href = strData and strData doesnt have headers. So the answer is, canvas2image does not support the feature we need, and we will need to try another solution. (for example perhaps FileSaver.js and canvas-toBlob.js)
http://eligrey.com/demos/FileSaver.js/
I want to read a directory and fill a list with the name of those files.
Is it possible to do this tasks using javascript?
No, for security reasons.
You might be able to do it by invoking ActiveX or Flash and having the user agree to permit file system access from these plugins, but - please don't.
Edit 10 years on:
Not only please don't do this, but now outside of using an old device without updates - you can't do this with Flash/ActiveX.
It's 2022, a lot of changes in the world and beyond, and, lo and behold, now we have something called File System Access API:
This API allows interaction with files on a user's local device, or on
a user-accessible network file system. Core functionality of this API
includes reading files, writing or saving files, and access to
directory structure.
It became available in Chrome 86 (released in October 2020). Safari added support in 15.2 version, released in the end of 2021. To the moment of writing this, Firefox doesn't support this feature though (here's the related discussion).
Also, security considerations didn't go anywhere:
This API opens up potential functionality the web has been lacking.
Still, security has been of utmost concern when designing the API, and
access to file/directory data is disallowed unless the user
specifically permits it.
This part is no longer relevant (kudos to #gignu for mentioning that in the comments) and is left here for historical reasons.
I suppose the closest you might get by using webkitdirectory attribute:
HTML
<input type="file" id="file_input" webkitdirectory="" directory="" />
<div id="list_of_files"></div>
...
JS
var $list = $('#list_of_files');
$('#file_input').change(function(event) {
var listOfFiles = event.target.files;
for (var i = 0, l = listOfFiles.length; i < l; ++i) {
$list.append($('<p>'+ listOfFiles[i].name +'</p>'));
}
});
... as shown here. But it works in Chrome only (and suggested usage of mozdirectory attribute didn't help).
You can try to use FileReader object, but it poorly supported by browsers.
In google chrome you may prompt the client to select a directory and then use this to list the files contained in the directory and its subdirectories:
<input type="file" webkitdirectory onchange="listContents(this.files)">
listContents would be your implementation.
I don't know if you're doing security research etc etc.. So besides from saying "you shouldn't do it", the actual answer to the question is, you can actually READ files by taking advantage poorly-written JS code, that's why you should code.. defensively.
Then there's this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Yes depending on the browser you have.
Even though it is not a common practice but you can using certain browsers such as Chrome (using the requestFileSystem supported by webkitRequestFileSystem) or in Internet Explorer using File System Object.
if (window.ActiveXObject) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\Program Files\\GM4IE\\scripts\\source.txt","C:\\Program Files\\GM4IE\\scripts\\target.txt", 1);
fso = null;
}
catch (e) {
alert (e.message);
}
}
I am getting error :
"Automation server can not create object" on the line where I am creating ActiveXObject instance.
I understand that it's considered very bad to access hard-drive data using javascript but I just need it.
I am using IE8 , Greasemonkey4IE to run my javascript.
Thank you,
Mohit
******************************
function WriteFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\source.txt","C:\\target.txt", 1);
}
I've put the above code inside a simple HTML page and it worked perfect.
http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm
You can find the similar code on above mentioned location.
I modified it a bit, tough.
But when I am trying to run it through GreaseMonkey4IE it simply spitting the same error I specified earlier.
I did it guys, but thanks a lot for your quick and helpful replies.
All I did is :
Go to Tools > Internet options > Security > Custom Level
Under the ActiveX controls and plug-ins, select Enable for Initializing and Script ActiveX controls not marked as safe.
Using native JavaScript, no, it is not generally possible to access a local file. Using plugins and extensions like ActiveX, Flash, or Java you can get around this rule, generally with some difficulty.
For some browser and OS specific exceptions to this general rule, you might want to have a look here:
Local file access with javascript
Note that as of late 2012, the FileReader API has been supported in all major browsers and provides a native JavaScript mechanism for accessing local files that the user nominates (via an input element or by dropping them into the browser).
This still cannot be used to access an arbitrary file by name/path as in the examples in the original question.
HTML5 File API has multiple ways to access local files.
window.requestFileSystem allows you to request access to the filesystem. Browser support is very poor on this (Chrome only).
FileReader is the HTML5 FileReader API that allows you to programatically read files that users select through a <input type='file' /> Browser support is better on this.
You should use fallbacks like flash and POST to a server for full file access.
Generally reading arbitary files is considered "cheating the browser" so I you'll either have to use secure HTML5, ActiveX or Flash. All 3 of those require user permissions.
After some research I have found:
var fso = new ActiveXObject("Scripting.FileSystemObject");
//This line will create a xml file on local disk, C drive
fh = fso.CreateTextFile( "C:\\fileName.xml", true);
fh.WriteLine("this is going to be written in fileName.xml");
This is how we can do it.There are other methods also.
Accessing local file system is very bad thing to do but yes we can do it.
Automation server can not create object
To get rid of this error go to Tools → Internet Options → Security → select Internet icon → click Custom level → select Enable for Initialize and script ActiveX controls not marked as safe for scripting.
I have not tested this on any other berowser except IE8, but I am sure it will work.