Javascript: cross-browser serverless file upload and download - javascript

So I'm working on a web app where a user will need to:
provide a file full of data to work on
save their results to a file
All the manipulation is done in javascript, so I don't really have a need for server-side code yet (just static hosting), and I like it that way.
In Firefox, I can use their file manipulation api to allow a user to upload a file directly into the client-side code (using a standard <input type=file/>) and create an object URL out of a file so a user can save a file created by the client-side code.
<input type="file" id="input" onchange="handleFiles(this.files)">
<a download="doubled" id="ex">right-click and save as</a>
<script>
function handleFiles(fileList){
var builder = new MozBlobBuilder();
var file = fileList[0];
var text = file.getAsBinary();
builder.append(text);
builder.append(text);
document.getElementById('ex').href = window.URL.createObjectURL( builder.getBlob() );
}
</script>
So this is great. Now I want to do the same in other browsers - or, at least, modern versions of other browsers. Do similar APIs exist for Chrome and IE? If so, has anyone already built a cross-browser wrapper that I should be using?

It's mostly available on Firefox 3.6+, Chrome 10+, Opera 11.1+, and hopefully Safari 6 and IE 10.
See: http://caniuse.com/#search=FileReader.

Check out FileSaver.js and the a[download] attribute (supported in Chrome dev channel). Blob (object) URLs have somewhat limited support right now.

Related

"Access is Denied" when embedding file from blob URL in IE

I have a web service that is sending the client a file as an arraybuffer which is then read into a blob object:
$scope.contentType = response.headers["content-type"];
$scope.file = new Blob([response.data], { type: $scope.contentType });
$scope.fileUrl = URL.createObjectURL($scope.file);
$scope.content = $sce.trustAsResourceUrl($scope.fileUrl);
I am using an object tag as the container:
<object id="documentContainer" ng-show="loaded" ng-attr-type="{{contentType}}" ng-attr-data="{{content}}" class="document-container"></object>
This works great in FF, chrome, mobile browsers, web browsers developed by alien species who have never had contact with humanity, etc., but not in IE.
When the data parameter of the object tag is set, IE responds in the console with
Error: Access is denied.
This seems to be some sort of security feature in IE where it doesn't want to use the file as a source because it resides on the client machine. It prohibits access even if you use javascript to create a brand new dom element with the data source set.
Microsoft provides their own blob methods like msSaveOrOpenBlob, but I need to be able to embed the file in the browser, not prompt the user to open the file in an external application.
Does anyone know of a workaround or way to embed the blob, which can be a wide variety of file types, in IE? I would hate to have to drastically refactor the web service and front end code just to accommodate IE, but it is looking like that might have to be the case.
I think the answer is "no". Our site generates PDF on the fly but we sniff the browser for what can be done with the returned PDF.
Example: http://www.cloudformatter.com/CSS2Pdf.Demos.Structures
If you are on Chrome you could select the "Embed PDF" here and it works like a charm ... if you are on IE, even if you select "Embed", it downloads the file. Because IE cannot and we just reroute anyone on IE to the download code.
http://caniuse.com/#feat=datauri
And don't get us started on what else is wrong on IE, several of the pages just broke because IE stopped serializing end tags for some "p" tags in the document.

How to open excel file using Javascript in chrome?

I have tried this code but it does not work in the chrome
var myApp = new ActiveXObject("Excel.Application");
myApp.workbooks.open("test.xls");
ActiveXObjects are only supported by IE. They don't work in Chrome.
ActiveXObject is available only on IE browser. So every other useragent will throw an error
On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

How to Enable JavaScript file API in IE8

I have developed a web application in asp.net, there is a page in this project which user should choose a file in picture format (jpeg, jpg, bmp,...) and I want to preview image in the page but I don't want to post file to server I want to handle it in client i have done it with java scripts functions via file API but it only works in IE9 but most of the costumers use IE8 the reason is that IE8 doesn't support file API is there any way to make IE8 upgrade or some patches in code behind I mean that check if the browser is IE and not support file API call a function which upgrades IE8 to IE9 automatically.
I don't want to ask user to do it in message I want to do it programmatically!!
even if it is possible to install a special patch that is required for file API
because customers thought it is a bug in my application and their computer knowledge is low
what am I supposed to do with this?
I also use Async File Upload Ajax Control But it post the file to server any way with ajax solution and HTTP handler but java scripts do it all in client browser!!!
following script checks the browser supports API or not
<script>
if (window.File && window.FileReader && window.FileList && window.Blob)
document.write("<b>File API supported.</b>");
else
document.write('<i>File API not supported by this browser.</i>');
</script>
following scripts do the read and Load Image
function readfile(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = readerHandler;
fr.readAsText(filename);
}
HTML code:
<input type="file" id="getimage">
<fieldset><legend>Your image here</legend>
<div id="imgstore"></div>
</fieldset>
JavaScript code:
<script>
function imageHandler(e2)
{
var store = document.getElementById('imgstore');
store.innerHTML='<img src="' + e2.target.result +'">';
}
function loadimage(e1)
{
var filename = e1.target.files[0];
var fr = new FileReader();
fr.onload = imageHandler;
fr.readAsDataURL(filename);
}
window.onload=function()
{
var x = document.getElementById("filebrowsed");
x.addEventListener('change', readfile, false);
var y = document.getElementById("getimage");
y.addEventListener('change', loadimage, false);
}
</script>
You can't install anything special to add support for File API in IE8. What you can do is use a polyfill in order to implement this functionality in browsers that don't natively support it. Take a look at this list of HTML5 Cross Browser Polyfills (you should find something suitable for you in File API / Drag and Drop section).
This works for me in pre IE10, i use https://github.com/eligrey/FileSaver.js for every other browser, note though this works it's not perfect, because it's IE and well you know what I mean
Hope this helps
/**
* saves File, pops up a built in javascript file as a download
* #param {String} filename, eg doc.csv
* #param {String} filecontent eg "this","is","csv"
* #param {String} mimetype eg "text/plain"
*/
function saveAs (filename, filecontent, mimetype) {
var w = window.open();
var doc = w.document;
doc.open( mimetype,'replace');
doc.charset = "utf-8";
doc.write(filecontent);
doc.close();
doc.execCommand("SaveAs", null, filename);
}
After some researches i have got there is no way to Enable file API in IE8 but, i got some thing that want to share it with you .....
Not directly, HTML 5 is not supported by IE8. There is addons for Canvas, and also there is Google Chrome Frame, a plugin to add HTML 5 to IE older than 9.
As i understood , Google Chrome Frame is perfect way to use HTML5.
It increases IE speed 10 times and also it's usage is very easy and i describe it for you all members...
Google Chrome Frame
A plugin for Internet Explorer that add to the Microsoft's browser, a full HTML 5 support and the JavaScript compiler of Chrome!
A stable version was released on September 22, 2010 and a lot of sites have added the code in their pages.
This plugin will work on Internet Explorer 6, 7 and further versions. Google wants to break a barrier that prevents the Web to evolve: the most common browser and its lack of compatibility with the new standards.
When it is recognized, Internet Explorer will run under WebKit, the rendering engine of Chrome and Safari, and the it will use the ultra-fast JavaScript compiler in replacement if the IE interpreter.
The advantage of this plugin is great for the compatibility of web applications and will become even more useful with WebGL integrated in Webkit, which let us have applications in 3D on the browser: a very different Web!
WebGL is also supported by Firefox since the version 3.7.
Since May 2011, the plugin can be installed without administrator rights, so on older version of IE which are incorporated into a server and can not be updated.
A tag in the code of a Web page will display a message prompting the user to download the plugin. Once it is installed, IE run as Chrome and will support HTML 5.
Features of Frame
The off-line mode.
The and tags. Microsoft also plans to implement them in IE.
Canvas.
WebGL.
CSS 3.
JavaScript compiler.
Compatibility at Acid 3 level.
See the vidéo.
Reaction from Microsoft
We were expecting that Microsoft has not appreciated really this initiative that promotes HTML 5 to the detriment of their own solution, Silverlight. The firm highlights a security problem:
Given the security issues with plug-ins in general and Google Chrome in particular, Google Chrome Frame running as a plug-in has doubled the attack area for malware and malicious scripts.
**
Chrome Frame. Automatic install. ->
http://www.google.com/chromeframe/?quickenable=true Google Chrome
Frame code. -> https://developers.google.com/chrome/chrome-frame/
Chrome Frame: Developer Guide. -> http://www.chromium.org/developers/how-tos/chrome-frame-getting-started
**

HTML 4 equivalent of HTML 5's FileReader?

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

How do I dynamically create a document for download in Javascript?

I'm writing some Javascript code that generates an XML document in the client (via Google Earth plugin). I'd like the user to be able to click a button on the page and be prompted to save that XML to a new file. If I were generating the XML server-side this would be easy, just make the button open the link. But the XML is generated client-side.
I've come up with a couple of hacks that half-work, inspired in part by this StackOverflow question. But neither completely work. Here's a demo HTML with embedded code:
<html><head><script>
function getData() { return '<?xml version="1.0" encoding="UTF-8"?><doc>Hello</doc>'; }
function dlDataURI() {
window.open("data:text/xml;charset=utf-8," + getData());
}
function dlWindow() {
var w = window.open();
w.document.open();
w.document.write(getData());
w.document.close();
}
</script><body>
<div onclick="dlDataURI()">Click for Data URL</div>
<div onclick="dlWindow()">Click for Window</div>
</body></html>
The dlDataURI() version works great in Firefox, poorly in Chrome (can't save), and not at all in IE. The Window() version works OK in Firefox and IE, and not well in Chrome (can't save, XML embedded inside HTML). Neither version ever prompts a user download, it always opens a new window trying to display the XML.
Is there a good way to do what I want in client side Javascript? I'd like this to work in today's browsers, ideally Firefox, MSIE 8, and Chrome.
Update with sample Downloadify code
window.onload = function() {
Downloadify.create("dlify", {
data: getData(),
filename: "data.xml",
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100, height: 30});};
The best I've seen as far is Downloadify by Doug Neiner, it requires Flash but works very well:
"A tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction."
Check this video.
If Flash is an option then the Flash Player (version 10+) offers the means for limited reading/writing of files from the local filesystem.
Check this out:
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/net/FileReference.html#save%28%29

Categories

Resources