Last active
August 29, 2021 14:40
-
-
Save scripting/35cadce5f0a19a26b62a2732cdea4622 to your computer and use it in GitHub Desktop.
Local file-chooser dialog in HTML and JavaScript. This app opens a text file on the local computer and displays the file text in the JavaScript console.
This file contains hidden or 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
function readFile (file) { | |
var url = window.URL.createObjectURL (file); | |
var reader = new FileReader (); | |
reader.onload = function (e) { | |
var filetext = reader.result; | |
console.log (filetext); | |
} | |
reader.readAsText (file); | |
} | |
function openDialogCommand (fileTypes) { | |
var theDialog = $("<input type=\"file\" accept=\"" + fileTypes + "\" style=\"display: none;\">"); | |
$(theDialog).change (function (event) { | |
if (this.files.length > 0) { | |
readFile (this.files [0]); | |
} | |
}); | |
$("body").append (theDialog); | |
$(theDialog).trigger ("click"); | |
} | |
function openTextFile () { | |
openDialogCommand (".html,.txt,.xml,.json,.opml") | |
} |
This file contains hidden or 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
<html> | |
<head> | |
<title>Open File Dialog</title> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="//s3.amazonaws.com/scripting.com/code/includes/jquery-1.9.1.min.js"></script> | |
<link href="//s3.amazonaws.com/scripting.com/code/includes/bootstrap.css" rel="stylesheet"> | |
<script src="//s3.amazonaws.com/scripting.com/code/includes/bootstrap.min.js"></script> | |
<script src="code.js"></script> | |
<style> | |
body { | |
font-family: Ubuntu; | |
font-size: 18px; | |
background-color: whitesmoke; | |
} | |
.divPageBody { | |
width: 60%; | |
margin-top: 50px; | |
margin-left: auto; | |
margin-right: auto; | |
margin-bottom: 400px; | |
} | |
p { | |
margin-top: 25px; | |
line-height: 140%; | |
} | |
a { | |
cursor: pointer; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="divPageBody"> | |
<h1>Open File Dialog</h1> | |
<p><a onclick="openTextFile ()">Click here to choose a file</a>.</p> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment