Created
May 22, 2012 00:29
-
-
Save precious/2765677 to your computer and use it in GitHub Desktop.
function to read file inside JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<script> | |
function handleFileSelect(input,callback) { | |
// used links: | |
// http://www.w3.org/TR/file-upload/ | |
// http://www.html5rocks.com/en/tutorials/file/dndfiles/ | |
// http://css.dzone.com/tips/javascript-how-read-and-write | |
if (window.File && window.FileReader && window.FileList && window.Blob) { | |
// in case of html5-compatible browser: | |
var file = input.files[0]; | |
var reader = new FileReader(); | |
reader.onload = function() { | |
callback(reader.result); | |
}; | |
reader.onabort = reader.onerror = function() { | |
callback(null); | |
}; | |
reader.readAsText(file); | |
} else if (window.navigator.userAgent.indexOf("MSIE ") > 0) { | |
// in case of IE: | |
try { | |
var fso = new ActiveXObject("Scripting.FileSystemObject"); | |
var file = fso.OpenTextFile(input.value,1); | |
var fileContent = file.ReadAll(); | |
file.Close(); | |
callback(fileContent); | |
return fileContent; | |
} catch (e) { | |
if (e.number == -2146827859) { | |
alert('Настройки безопасности браузера не позволяют получить доступ к локальным файлам. Чтобы исправить это, ' + | |
'зайдите в Сервис->Свойства обозревателя->Безопасность->Уровень безопасности для этой зоны->Другой. '+ | |
'Найдите пункт "Использование элементов управления ActiveX, не помеченных как безопасные для использования" ' + | |
'и измените его на "Предлагать" или "Включить"'); | |
//'Unable to access local files due to browser security settings. ' + | |
//'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + | |
//'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); | |
} | |
} | |
} else { | |
// client isn't supported: | |
callback(null); | |
} | |
} | |
function callback(text) { | |
if (text == null) | |
return; | |
var splited = text.split('\n'); | |
for (var i = 0;i < splited.length;++i) | |
splited[i] && (document.getElementById('list').innerHTML += '<br>' + i + '. ' + splited[i]); | |
} | |
</script> | |
</head> | |
<body> | |
<input type="file" id="files" onchange="handleFileSelect(this,callback)"> | |
<div id="list"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment