Internet Explorer 11 get file size - javascript

I'm trying to get the size of a file from a file-input control.
To do this I'm using jquery:
function init() {
$("#cphInhalt_cphInhalt_file0").bind("change", function() {
handleFileSelect(this);
});
}
function handleFileSelect(e) {
if (e.files[0].size + totalFileSize > 3000000) {
addNewUpload(e);
$(e).remove();
if (getCookie("language") == "German") {
alert("Die gesamte Dateigröße wurde überschritten");
} else {
alert("The total file size has been exceeded");
}
return;
}
In any browser this works fine, except of Internet explorer ( using version 11) , but as I think it should support the File Api right?
It says e.files is undefinied

It will ask for Enable ActiveX in your browser, please say allow
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
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>
This ans was given in how validate file size using HTML and Javascript on client side

The problem was, that the IE set himself into a Version 7 compatibility mode.

Related

File Input stopped working in Instagram in-app browser (Android only)

input type="file" stopped working in Android Instagram in-app browser recently. It was working fine earlier. It still works fine in iOS. I also tested it in Facebook in-app browser which also works fine on both Android and iOS.
Here is my simple test codes.
<!DOCTYPE html>
<html>
<head>
<title>File Validation</title>
</head>
<body>
<p>
<input type="file" id="file" onchange="checkFileSize()" />
</p>
<p id="size"></p>
</body>
<script>
var checkFileSize = function() {
var input = document.getElementById('file');
if (input.files.length > 0) {
for (var i = 0; i < input.files.length; i++) {
var fsize = input.files[i].size;
var file = Math.round((fsize / 1024));
document.getElementById('size').innerHTML = '<b>' + file + '</b> KB';
}
}
}
</script>
</html>
It just prints the file size on selection of a file. I have also uploaded the html to my Amazon S3 for easier testing. Here is the page link - https://virtueplanet.s3.amazonaws.com/testfile/index.html
If you open the link in Instagram in-app browser and select a file from your phone then it always returns the file size as zero (0). I also tried to read the file using Filereader which also fails.
var input = document.getElementById('file');
if (input.files.length > 0) {
for (var i = 0; i < input.files.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
alert('Image loaded.');
}
reader.onerror = function() {
alert(reader.error.message);
}
reader.readAsDataURL(input.files[i]);
}
}
It appears to be bug in the recent Instagram App update for Android. Any help will be highly appreciated.

JS oop not work in Internet Explorer

I'm developping a web site using WAMP, this is a part of code in my website. I even checked this block of code mentioned below.
html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="Functions/jquery.min.js"></script>
<script type="text/javascript" src="Functions/listControl.js"></script>
<script type="text/javascript">
var users= new regUsers('load','bef','full');
</script>
</head>
<body>
</body>
</html>
javascript page
function regUsers(id,pos,detail)
{
/*
usr001 all users
usr002 search users on keyword
*/
var self=this
this.count=0;
this.id='#' + id;
this.pos=pos;
this.amount=0;
this.detail=detail;
this.countReset= function(){this.count = 0;};
this.getList=function()
{
console.log('count : ' + self.count);
$.ajax({
type:'POST',
url:'Functions/list.php',
data:{req:'usr001',off:this.count,detail:this.detail,amount:self.amount},
success:function(ans){
if(ans=="")
return;
else
{
self.count += parseInt(self.amount);
switch(self.pos)
{
case 'bef':
$(ans).insertBefore(self.id);
break;
case 'app':
$(self.id).append(ans);
console.log(ans);
break;
}
}
}
});
}
this.findRec=function(keyW='',cls,field)
{
if(keyW=='')
{
self.getList();
return;
}
$.ajax({
type:'POST',
url:'Functions/list.php',
data:{req:'usr002',keyW:keyW,detail:this.detail,field:field},
success:function(ans){
self.countReset();
$("."+ cls).remove();
switch(self.pos)
{
case 'bef':
$(ans).insertBefore(self.id);
break;
}
}
});
}
}
This code is properly work in Firefox, but not in internet explorer. In Internet explorer console, it is said that regUsers is not difined.
It could be that Internet Explore loads the JS files after it loads the inline script, I know it may not make much sense to do that but it might be a particular IE issue. What you could do is put your var users= new regUsers('load','bef','full'); in a third JS file or you can assign the value to users in unload of the body tag i.e.
<body onload="users = new regUsers('load', 'bet', 'full')">
. . .
</body>
This will insure that the your initialization code is executed after the webpage has loaded. Since users is declared with var it becomes a global variable, declaring with var users = … would have made it visible only in the scope of onload.

Get text file content using javascript

I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

IE losing iframe contents after back/forward key

This problem is only happening in IE (at least 8 and 9). After an element is dynamically added to the DOM, the contents of an embedded iframe are lost when the page is reentered with a BACK/FORWARD key. Just two small HTML files will reproduce the issue.
The first file is iframe.htm:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function mytrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b); /// will work if commented
}
function submitListing() {
mytrace('submitListing()');
var doc = document.getElementById("output_iframe")
.contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//mytrace('submitListing(): out');
}
</script>
</head>
<body>
<div id="trace_output"><br /></div>
<input type="button" onclick="submitListing();" value="Run" /><br />
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
The second file is report.htm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
LINK
</body>
</html>
Steps to recreate the issue (BACK KEY)
Place above content in two files
Browse the iframe.htm file
Press the Run button to load report.htm in the iframe
Click on the LINK link to load a different page
Press the browser BACK button to returned to the "cached" (lmao) page
iframe contents are gone!!!! (only in IE-- safari, chrome, firefox retain the contents)
Also..(FORWARD KEY)
Browse to an arbitrary page (for history, http://www.google.com works)
Load iframe.htm into the same tab
Press the Run button to load report.htm in the iframe
Press the browser BACK button to return to the first page
Press the browser FORWARD button to return to iframe.htm
iframe contents are gone again!!
Now comment out the line:
d.appendChild(b)
That one change allows everything to work in IE. However, my solution needs to make those kinds of DOM manipulations (heavy jQuery/AJAX app) AND be able to restore the iframe across browser BACK/FORWARD actions.
It seems that I will have to remember the contents of the iframe so that I can restore it when the page is accessed with the BACK/FORWARD keys. I'm not thrilled with this because sometimes the iframe content will be quite large and it could chew up a bit of memory and time to make another copy of the embedded document for the restore. I would love to hear some other ideas about how I could approach this. Thanks in advance.
EDIT
The following replacement to iframe.htm will work around the problem with IE. I'm going to rewrite this using jQuery and add some more logic to restore the scroll positions. I had hoped for something more elegant, but this is doing the job.
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function myTrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b);
}
var make_backup ="false";
function submitListing() {
make_backup = "true";
myTrace('submitListing()');
var doc = document.getElementById("output_iframe").contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//myTrace('submitListing(): out');
}
function iframe_load() {
myTrace("iframe loaded, is_cached=" + document.getElementById("is_cached").value);
if (make_backup == "true") { // only when submitting
var htm, doc;
make_backup = "false"
doc = document.getElementById("output_iframe").contentWindow.document;
htm = doc.documentElement.innerHTML;
document.getElementById("iframe_backup").value = htmlEscape(htm);
}
}
function bodyLoaded() {
var is_cached = document.getElementById("is_cached");
if (is_cached.value == "false") { // initial page load
is_cached.value = "true";
}
else { // BACK or FORWARD, restore DOM where needed
var htm;
htm = htmlUnescape(document.getElementById("iframe_backup").value);
var doc;
doc = document.getElementById("output_iframe").contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
}
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body onload="bodyLoaded();">
<div id="trace_output" style="height: 300px; border-width:1; background-color: Silver"><br></div>
<input id="is_cached" type="hidden" value="false">
<input id="iframe_backup" type="hidden">
<input type="button" onclick="submitListing();" value="Run"><br>
<iframe id="output_iframe" src="" onload="iframe_load();"></iframe>
</body>
</html>
EDIT 2
Rewritten with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe workaround2</title>
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
var make_backup = "false";
$(document).ready(function () {
myTrace('document ready()');
var is_cached = $("#is_cached");
if (is_cached.val() == "false") { // initial page load
is_cached.val("true");
}
else { // BACK or FORWARD, restore DOM where needed
if ($.browser.msie) { // IE loses iframe content; restore
var htm = htmlUnescape($("#iframe_backup").val());
var doc = $("#output_iframe")[0].contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
myTrace('iframe contents restored');
}
}
$('#output_iframe').load(function () {
myTrace("iframe_loaded");
if (make_backup == "true") { // only when submitting
make_backup = "false"
if ($.browser.msie) {
var doc = $("#output_iframe")[0].contentWindow.document;
var htm = doc.documentElement.innerHTML;
$("#iframe_backup").val(htmlEscape(htm));
myTrace('iframe contents backed up');
}
}
});
$('#submit_listing').click(function () {
make_backup = "true";
myTrace('submitListing()');
var doc = $("#output_iframe")[0].contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache='+d.getTime());
});
});
function myTrace(msg) {
$('#trace_output').append(msg + '<br>');
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body>
<div id="trace_output"
style="height: 300px; border-width:1; background-color: Silver">
<br></div>
<div style="display: block;">
<input id="is_cached" type="text" value="false">
<input id="iframe_backup" type="text" type="hidden"></div>
<input id="submit_listing" type="button" value="Run"><br>
<iframe id="output_iframe" src=""></iframe>
</body>
</html>

Redirection to a locale page with a Firefox extension

I'd like to have a page redirecting to another using Javascript. I've tried with document.location.href but it doesn't work with local pages (stored in my hard drive).
Does someone know something that would do the trick ?
thanks,
Bruno
Doesn't it? I've tried the following and it works fine:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<input type="text" value="" id="test"/>
</body>
<script type="text/javascript">
document.location.href = "file:///C:/dev/PICCS/vb/binaries/";
</script>
</html>
Tested in IE8 and Chrome
Posting this on the xul file of the extension :
function Read(file)
{
var ioService=Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var scriptableStream=Components
.classes["#mozilla.org/scriptableinputstream;1"]
.getService(Components.interfaces.nsIScriptableInputStream);
var channel=ioService.newChannel(file,null,null);
var input=channel.open();
scriptableStream.init(input);
var str=scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
}
gBrowser.addEventListener("DOMContentLoaded", function(e) {
var documentElement = e.originalTarget.defaultView.document;
var div = documentElement.createElement("div");
div.innerHTML = Read("chrome://firefox_extension/content/locale.html");
documentElement.body.appendChild(div);
},
false
);
the complete extension : http://uploadingit.com/file/xef7llflgmjgfzin/my_firefox_extension.xpi

Categories