Storing variables from parsed text file using javascript - javascript

The text file contains information that I want to use with my website for logging in purposes
Text file contains the following..line by line
user:password
user2:user2password
I have tried using blob to read the text file but variables are not getting stored so I would like to know where I am going wrong or if I am even able to read the file using this method
function readFile(){
var fileName = txtName.value;
file = login.txt;
var blob = file.read();
var readText = blob.text;
var lines = data.split("\n && : " );
//Adding the file content to the label placed
lblFileContent.setText(readText);
Ti.API.info(readText);
// dispose of file handle & blob.
file = null;
blob = null;
}

I've used this in the past to read a txt-file:
JavaScript (jQuery):
function readFile() {
$.post('path/to/php/read_file.php', {
dir: 'path/to/file',
file: 'file_name.txt',
},function(file_contents) {
if (file_contents != '') {
//your code here
}
});
}
PHP:
<?php
/* This script is invoked by 'index.html'.
* This script gets the content of the file that has been changed by
* the admin, and uses it to determine the path of the file
* that is currently set by the admin.
*/
$dir = $_POST["dir"];
$file = $_POST["file"];
$contents= '';
if ($dhandle = opendir("$dir")) {
while (false !== ($entry = readdir($dhandle))) {
if ($entry != "." && $entry != "..") {
if ($entry == $file) {
$entry_path = $dir.DIRECTORY_SEPARATOR.$entry;
$fhandle = fopen($entry_path, 'r');
$value = fread($fhandle, filesize($entry_path));
fclose($fhandle);
}
}
}
closedir($dhandle);
echo "$contents";
}
?>

You might want to try HTML 5 file API
1) To specify the text file add an input type file HTML tag (this will show a file selection dialog, if clicked).
<input type="file" id="myFileId">
2) Add a listener that will be executed when you choose a file, which triggers a 'change' event.
document.getElementById('myFileId').addEventListener('change', function(e) {
});
3) In the EventListener use FileReader to read your text file.
document.getElementById('myFileId').addEventListener('change', function(e) {
var file = document.getElementById('myFileId').files[0];
var reader = new FileReader();
reader.onload = function(e) {
var userPass = reader.result.split(" "); // split by space
// userPass is an array where each element has a user:pass
// do your stuff
} // onload
reader.readAsText(file);
});
You might want to check for file type/size before trying to read it.

Here is a solution you may be interested in.
Text file named login.txt containing I'm reading this file using JavaScript.
user
myuser
password
myuserpassword
My JavaScript code
var loadXMLDoc=function(){
var Credentials={};
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==0){
var temp=xmlhttp.responseText.split('\n');
for(i=0;i<temp.length;i++){
switch(temp[i].trim()){
case "user":
case "User":
Credentials.Username=temp[i+1];
break;
case "password":
case "Password":
Credentials.Password=temp[i+1];
break;
}
}
console.log(Credentials); //Printing the object in the console.
}
}
xmlhttp.open("GET","login.txt",true);
xmlhttp.send();
}
HTML input. Please note I'm call the js function here.
<input type="button" id="load" value="Click me!" onclick="loadXMLDoc();"/>
Print the password in console with a function getPassword("myuser").
var getPassword=function(username){ // It takes one string parameter which is the username.
var password="";
if(Credentials.Username){
if(Credentials.Username.trim()==username) password=Credentials.Password;
}
return password;
};

Related

If image url not exist on server replace url with other (multiple time)

I made lastposter avatar for my forum system.
What i want : when user avatar img not exist change file type multiple time. Such example; if user_{userid}_avatar.png not exist change url to user_{user_id}_avatar.jpg and again it's not exist change to user_{userid}_avatar.gif and etc.({user_id} coming as php variable that's no matter).
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
<div class="lpavatar"><img src="/avatar/user_{user_id}.png"/></div>
You can do something like this:
Javascript:
var img_types = ['jpeg', 'gif', 'png'];
var avatar = '';
for(var i=0;i<img_types.length();i++) {
avatar = new File("/path/to/avtar." + img_types[i]);
// See if the file exists
if(avatar.exists()){
break;
}
}
PHP:
<?php
// put allowed image types in this array
$img_types = ['jpeg', 'gif', 'png'];
// avatar URL will be stored in here
$avatar = '';
// loop over the image_types array
foreach($img_types as $img_type) {
$avatar = '/path/to/user_{userid}_avatar.' . $img_type;
// check if the files exists
if(file_exists($avatar)) {
// exit the foreach loop, because we found the image
break;
}
}
?>
You can use a function like this.
function image_exists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}

JAVASCRIPT - Read local file, filter for a word and print word's line

I have the following code. It can open a file and display it in the browser. But I want to:
- Select many files instead of one;
- Then Filter on these files for a word (username);
- Then print username's line (text file: username xxxx);
- If the word "username" is not found , print - text file: not found
Any idea?
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('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 { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
I havent tested this, but does the basic idea work? Read the files through a for-loop, and search for your target string. If you get to the end and you dont find it, return your empty message;
function SearchFiles(var target_string, var file_paths){
var fs = require("fs");
my_file_paths.foreach(function(filepath){
var text = fs.readFileSync(filepath);
var pos = text.search(target_string);
if (pos>1) {
return text.substring(pos, pos + target_string.length);
}
}
return "not found"
}
// now to use the function
var my_file_paths; // init this to what you want to search through
var target_username; // init this as well
var found_username = SearchFiles(target_username, my_file_paths);
DisplayContents("text file: " + found_username);

get a file as a string using javascript

I have a HTML form to upload a file.
My goal is to submit the form, check that the file has XML extension and get the file as a String into a JavaScript variable.
Then, I want to send a POST request to the server using this String.
Any idea how I can do that?
My goal is to submit the form, check that the file has XML extension and get the file as a String into a JavaScript variable.
I don't think you really mean you want to submit the form (as in, send it to the server) at this stage.
Then, I want to send a POST request to the server using this String.
You can do that on browsers that support the File API, which is most modern ones but not IE8 or IE9. There's an example in this answer.
Basically, you get the File instance from your <input type="file"> element's files list, check its name, read it, and then post it:
Complete Example (source) (other than the POST bit, which I assume you know how to do):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<input type="file">
<button>Go</button>
<script>
(function() {
"use strict";
// Get our input element and our button; in this example there's
// just one of each, you'd narrow down these selectors of course
var inputElement = document.querySelector("input[type=file]"),
button = document.querySelector("button");
if (typeof FileReader !== 'function') {
alert("The file API isn't supported on this browser.");
inputElement.style.display = button.style.display = "none";
return;
}
if (!inputElement.files) {
alert("Odd, this browser has FileReader but no `files` property on the input element.");
inputElement.style.display = button.style.display = "none";
return;
}
button.addEventListener("click", function() {
var file, filename, reader, filedata;
// Does it have any files?
if (inputElement.files.length === 0) {
alert("No file chosen");
return;
}
// Get its first file
file = inputElement.files[0];
// Get its name in lower case
filename = file.name.toLowerCase();
// XML extension?
if (filename.substr(-4) !== ".xml") {
alert("Please only choose .xml files");
}
else {
// Yes, read it
reader = new FileReader();
reader.onload = function() {
// Get the file data, note that this happens asynchronously
filedata = reader.result;
// Send your POST with the data; here, we'll just dump it out
// as text
displayXml(filedata);
};
reader.readAsText(file); // or you can use readAsBinaryString
}
}, false);
function displayXml(xmlText) {
var pre = document.createElement('pre');
pre.innerHTML = xmlText.replace(/&/g, "&").replace(/</g, "<");
document.body.appendChild(pre);
}
})();
</script>
</body>
</html>

Javascript XMLHTTPRequest Not Posting XML File

I have a content generator which contians textboxes, textareas and file input controls. All controls are in HTML. Once the save button is clicked I create my XML Document with the text entered into the HTML controls. Finally, I would like the user to be prompted to download the XML File. I am hoping I can do this using a POST method with a XMLHTTPRequest in Javascript. Once the XML Document is sent with the XMLHTTPRequest here is what happens,
Chrome: HTTP Status Code: 304
IE10: Nothing happens
Again, I would like the browser to prompt the user to download the XML File. Here is my code.
function generateBaseNodes() {
var xmlString = '<?xml version="1.0"?>' +
'<sites>' +
'<site>' +
'<textareas>' +
'</textareas>' +
'<textboxes>' +
'</textboxes>' +
'<images>' +
'</images>' +
'</site>' +
'</sites>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDocument = parser.parseFromString(xmlString, "text/xml");
}
else // Internet Explorer
{
xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
xmlDocument.async = false;
xmlDocument.loadXML(xmlString);
}
return xmlDocument;
}
function saveXmlFile(xmlDocument) {
if (window.XMLHttpRequest) { // IE7+, Chrome. Firefox, Opera. Safari
xmlhttp = new XMLHttpRequest();
}
else { // IE5 & IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('POST', 'http://localhost:57326/ContentGenerator.html', true);
xmlhttp.setRequestHeader('Content-type','text/xml');
xmlhttp.send(xmlDocument);
}
$('document').ready(function () {
$('#templateTab a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
//Create TextArea XML elements and add them
$('#btnSave').click(function () {
var x;
var xmlDocument = generateBaseNodes();
$('.content').each(function () { // Textarea
if ($(this).attr('id') != undefined) {
if ($(this).is('textarea')) {
// create article node with control id.
articleNode = xmlDocument.createElement($(this).attr('id'));
// append node to xmldocument
x = xmlDocument.getElementsByTagName('textareas')[0];
x.appendChild(articleNode);
// append text
articleNode.appendChild(xmlDocument.createTextNode($(this).text()));
}
if ($(this).is('input[type=text]')) { // Textbox
textNode = xmlDocument.createElement($(this).attr('id'));
x = xmlDocument.getElementsByTagName('textboxes')[0];
x.appendChild(textNode);
textNode.appendChild(xmlDocument.createTextNode($(this).text()));
}
} else { // Show error if a control does not have an ID assigned to it.
alert('The' + $(this).prop('type') + 'has an undefined ID.');
}
});
$('.imageContent').each(function () {
if ($('.imageContent input[type=file]')) { // Image url
// Validate file is an image
switch ($(this).val().substring($(this).val().lastIndexOf('.') + 1).toLowerCase()) {
case 'gif': case 'jpg': case 'png':
imageNode = xmlDocument.createElement($(this).attr('id'));
x = xmlDocument.getElementsByTagName('images')[0];
x.appendChild(imageNode);
imageNode.appendChild(xmlDocument.createTextNode($(this).val()));
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
}
});
saveXmlFile(xmlDocument);
});
});
I SUPPOSE I SHOULD POST MY XML OUTPUT
<sites>
<site>
<textareas>
<article1>sfdsfd</article1>
<article2>dsfsdf</article2>
</textareas>
<textboxes>
<title>dsfdsf</title>
<contentHeader>sdfsdf</contentHeader>
<linkContent>sdf</linkContent>
<link>sdfsd</link>
<relatedContent>sdfsdf</relatedContent>
<contentLink>dsf</contentLink>
<relatedArticle>sdfa</relatedArticle>
<articleLink>sfdf</articleLink>
</textboxes>
<images>
<imageHeader>C:\Images\Header.png</imageHeader>
<articleImage>C:\Images\Main.png</articleImage>
<articleImage2>C:\Images\Deals.png</articleImage2>
</images>
</site>
</sites>
Is there any way to make the browser prompt to download the XML File?
Yep. Convert your data to Blob, then generate a URL from it, which you can then use in an <a>, give that <a> a download attribute and the browser now knows it's to be saved not opened, then finally simulate a click on it. For example;
function txtToBlob(txt) {
return new Blob([txt], {type: 'plain/text'});
}
function genDownloadLink(blob, filename) {
var a = document.createElement('a');
a.setAttribute('href', URL.createObjectURL(blob));
a.setAttribute('download', filename || '');
a.appendChild(document.createTextNode(filename || 'Download'));
return a;
}
function downloadIt(a) {
return a.dispatchEvent(new Event('click'));
}
// and use it
var myText = 'foobar',
myFileName = 'yay.txt';
downloadIt(
genDownloadLink(
txtToBlob(myText),
myFileName
)
);
Try using Filesaver.js to get the user to download a file in memory.
Look also into Data URI's like this:
text file

How to download multiple files in one shot in IE

I want to download multiple files on click of a button in jsp.
I am using the following code in the js to call one servlet twice.
var iframe = document.createElement("iframe");
iframe.width = iframe.height = iframe.frameBorder = 0;
iframe.scrolling = "no";
iframe.src = "/xyz.jsp?prodId=p10245";
document.getElementById("iframe_holder").appendChild(iframe);
var iframe2 = document.createElement("iframe");
iframe2.width = iframe2.height = iframe2.frameBorder = 0;
iframe2.scrolling = "no";
iframe2.src = "/xyz.jsp?prodId=p10243";
document.getElementById("iframe_holder").appendChild(iframe2);
In xyz.jsp i am calling the servlet which downloads the file from a path and send it on the browser.
Issue is that it is working safari,firefox but not in IE.
We cannot download multiple files with IE?
By design, non-user-initiated file downloads are blocked in IE. That inherently means that it should not be possible to download more than one file as the result of a single user-click.
I've used the following code to download multiple files in IE and Chrome
function downloadFile(url)
{
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function downloadFiles(urls)
{
downloadFile(urls[0]);
if (urls.length > 1)
window.setTimeout(function () { downloadFiles(urls.slice(1)) }, 1000);
}
You pass an array of URLs to the downloadFiles() function, which will call downloadFile() for each with a short delay between. The delay seems to be the key to getting it to work!
I had a similar need but also wanted the downloads to occur in a new window.
I created a js to download a list of files, and a php to do the actual file saving. I used the above as a starting point, and the PHP start from (okay, can't find the original source). I encode the passed URI so spaces in the file names don't cause troubles.
(function () {
"use strict";
var files = [], // Array of filename strings to download
newWindow, // New window to handle the download request
secondsBetweenDownloads; // Wait time beteen downloads in seconds
//
// Download a file using a new window given a URI
//
function downloadFile(uri) {
if (!newWindow) {
newWindow = window.open('',
'',
'width=1500 height=100');
}
if (newWindow) {
newWindow.location =
'saveAs.php?' +
'file_source=' + encodeURI(uri);
newWindow.document.title = "Download File: " + uri;
} else {
console.log("Unable to open new window. Popups blocked?");
}
}
//
// Download all files specified in the files[] array from siteName.
// Download the file at array position zero, then set a timeout for
// secondsBetweenDownloads seconds
//
function downloadFiles(siteName) {
var showTime = new Date();
console.log(
showTime.toTimeString().substring(0,8) +
" Starting download for: " + files[0]
);
// Skip any empty entries, download this file
if (files[0].length > 0) downloadFile(siteName + files.splice(0, 1));
if (files.length > 0) { // If more files in array
window.setTimeout(function () { // Then setup for another iteration
downloadFiles(siteName );
}, secondsBetweenDownloads * 1000); // Delay for n seconds between requests
} else {
newWindow.close(); // Finished, close the download window
}
}
//
// Set the web site name and fill the files[] array with the files to download
// then kick off the download of the files.
//
$(document).ready(function () {
var
siteName** = "http://www.mysteryshows.com/thank-you/";
secondsBetweenDownloads** = 35; // N seconds delay between requests
files = [
"show1.mp3",
"show2.mp3"
];
downloadFiles(siteName, files);
});
}());
The HTML for the page is simple. Basically any syntax-compliant page will do.
The saveAs.php page which the js file uses in the newWindow.location line is php only.
<?php
if (isset($_GET['file_source'])) {
$fullPath = $_GET['file_source'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to
// force a download
header("Content-type: application/pdf"); // add here more headers for
// diff. extensions
break;
default;
header("Content-type: **application/octet-stream**");
header("Content-Disposition:
filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
$request = $path_parts["dirname"] . '/' .
rawurlencode($path_parts["basename"]);
readfile($request);
exit;
}
}
?>
I used rawurlencode on just the 'basename' portion of the URI to ensure it was a valid, encoded request.
It can be done by creating a blob using the file source URL. I have tested this with image and PDF files in IE 11.
if (navigator.msSaveBlob) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file_url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
navigator.msSaveBlob(blob, file_name);
}
}
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
}
xhr.send();
}
I got this idea when I came across this: Getting BLOB data from XHR request

Categories

Resources