try to parse the log by using javascript, and nothing shown - javascript

I am quite new in Javascript, and I am trying to parse the log something like
2014-02-25T,ip='99.114.',rm=GET,rv=HTTP/1.1,rs=200,rt=0.787020,ru='/tag/febe1eab436e98eb4ed3711870496c91/st.js?l=http%3A%2F%2Fwww.michaels.com%%2Fon%2Fdemandware.store%2FSites-Michaels-Site%2Fdefault%2F-scrapbooking',cl=996,rr='http://www.michaels.com/videos/KBPP1Vm3075,default,pg.html?fdid=videos-scrapbooking',
I want to separate them by ',', and only show 'rr' attribute. Following is my code, and when I run it, there is nothing shown.
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
var str = output;
var start =0;
var end = 0;
while (end<str.length){
while (end<str.length && str.charAt(end)!=',') {
end++;
}
var stringLine="";
if (end==str.length) {
stringLine = str.substring(start, str.length);
}else {
stringLine = str.substring(start, end+1);
}
var signIndex=0;
while (stringLine.charAt(signIndex)!='=') {
signIndex++;
}
var newSubString = stringLine.substring(0,signIndex);
if (newSubString==="ip"){
document.write(stringLine);
document.write("<br />");
}
start=end+1;
end=start;
}
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>

Related

Javascript delay not working. Tried too many things [duplicate]

This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 1 year ago.
I am new with JavaScript programming. I am making a program for deaf and blind children community. It is text to display Letters program. It split text and show image on screen.
How it works:
HTML and JavaScript base program. Input sentence taken from user. JavaScript split it and send relevant image name to HTML for display.
Problem:
It shows all images at once without delay. When I use alert() it shows all images are being displayed. 3rd day going on I tried to implement delay timebase substraction or settimeout but not working. Perhaps I am doing something wrong. I need community help to fix this.
Code:
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="index.css" />
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<title>Image Changer</title>
</head>
// How to change image SCR through javascript.
<body>
<input id="txt" name="txt" type="textbox" />
<img id="image1" src="./multimedia/alphabets/0.jpg" style="width:100px">
<button onclick="imagechange((document.getElementById('txt').value) , document.getElementById('image1.scr'))">Button</button>
<script type="text/javascript">
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
alert(txt1);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " )
document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}
</script>
</body>
</html>
setTimeout is async so that's probably the reason it did not work. To make it work, you can do something like this
<script type="text/javascript">
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
async function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
await delay(1000);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}
</script>
I made a delay promise from the setTimeout and made your imageChange function async so I can await the delay promise during each loop.
I guess this is because DOM manipulation is synchronous and DOM rendering is asynchronous. Actually you can try this:
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
alert(txt1);
document.getElementById('image1').src = imagefolderlocation + txt1 +".jpg";
if(txt1 == " " ) document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
console.log(document.getElementById('image1').src);
}
}
You can see the result in the console, image1.src did change but was not rendered.
To make it work, you can use the asynchronous function like this if you are using ES5:
function imagechange(txt,image1){
var txt1 = "";
var txt2 = "";
var imagefolderlocation = "./multimedia/alphabets/";
for (var i = 0; i < txt.length;i++) {
txt1 = txt.charAt(i).toUpperCase();
// Use closures to avoid the problems caused by the txt1 variable context
function imageChange(imageName) {
setTimeout(function () {
document.getElementById('image1').src = imagefolderlocation + imageName +".jpg";
if(txt1 === " " ) {
document.getElementById('image1').src = imagefolderlocation + "Blank.jpg";
}
}, 1000 * i); // Change image1.src after i seconds
}
imageChange(txt1);
}
}
Btw, you should use <!-- How to change image SCR through javascript. --> in HTML if you want to add comments.

Html & js not showing image

So the problem is that I want to create an img element with the same src as the insert file but its not working and I dont know why, here is the code:
<!DOCTYPE html>
<html>
<head>
<title>HMM...</title>
</head>
<body>
<input type="file" id="wowo">
<div id="dispImg">
</div>
<button onclick="wp()">run</button>
<script>
window.URL = window.URL || window.webkitURL;
function wp() {
var file = document.getElementById("wowo").value;
var nopath = file.substring(12);
alert(nopath);
var crimg = document.createElement("img");
crimg.src = window.URL.createObjectURL(nopath);
crimg.height = 60;
crimg.onload = function() {
window.URL.revokeObjectURL(this.src);
}
document.getElementById("dispImg").appendChild(crimg);
}
</script>
</body>
</html>
Thank you.
You can try this code:
function wp() {
var files = document.getElementById("wowo").files;
// FileReader support
if (FileReader && files && files.length) {
var crimg = document.createElement("img");
var fr = new FileReader();
fr.onload = function () {
crimg.src = fr.result;
}
fr.readAsDataURL(files[0]);
crimg.height = 60;
document.getElementById("dispImg").appendChild(crimg);
}
}
This is a demo https://jsbin.com/qaqoveq

what's wrong with these code? why it not sort preview image upload?

Here is the full code for html5 multiple upload file with removeable and preview image
but I don't know in function handleFileSelect(e) why it show the preview images with wrong sorting when choose more than 2 files? (Although, it upload to my folder correctly sort but I still want it to show preview with correct sorting)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
}
.delete_img{
cursor:pointer;
color:red;
font-size:14px;
margin-left:10px;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".delete_img", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
filesArr.forEach(function(f) {
if(!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'> <span class='delete_img'> DEL </span><br>" + f.name + "<br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var username = document.getElementById('username').value; //get value จาก form input
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username); //มาใส่ในajax object formdata เพื่อเตรียมส่งเข้าฝั่งserver
data.append('email', email);
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]); //อย่าลืม []
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
//alert(e.currentTarget.responseText + ' items uploaded.');
window.location = "http://www.google.com";
}
}
xhr.send(data);
}
function removeFile(e) {
var img = e.target.parentElement.querySelector("img")
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
Maybe the total upload size of your files overcomes the max_upload_limit.Usually is 2 MB.As i tested your code in liveweave i don't have problem (5 images).Check the total size of your files. How much is it?

To get the name from input file type and display in a p tag through javascript.

I am trying to get the name from input file type to display the name in a p tag, below is my code, advance thanx to all.
<script type="text/javascript">
var path = document.getElementById("photo").value;
var filename = path.substring(path.lastIndexOf("/") + 1);
document.getElementById("log").innerHTML = filename;
</script>
<input type="file" id="photo"/>
<p id="log"></p>
Try below code...
Demo Fiddle
var input = document.getElementById("photo");
input.onclick = function () {
this.value = null;
};
input.onchange = function () {
var path = input.value;
var filename = "";
if(path.lastIndexOf("\\") != -1)
filename = path.substring(path.lastIndexOf("\\") + 1,path.length);
else
filename = path.substring(path.lastIndexOf("/") + 1,path.length);
document.getElementById("log").innerHTML = filename;
};
I assume that you's trying to get the name of the file. Below is the code of doing that:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
function showfile()
{
var path = document.getElementById("photo").value;
var filename = path.substring(path.lastIndexOf("\\") + 1);
document.getElementById("log").innerHTML = filename;
}
</script>
</head>
<body>
<input type="file" id="photo" onchange="showfile()"/>
<p id="log"></p>
</body>
</html>

trying to leverage JSZip to open and then parse a specific file in a .zip

Have been trying to use the JSZip library to cycle through files in a .zip, looking for one (here, test.txt) that I want to parse for content.
Have attempted to do a modification of the sample [recommend viewing source on that] that JSZip provides:
<!DOCTYPE HTML>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div class = "container">
<div class = "hero-unit">
<input type="file" class="span7" id="input" name="file" multiple /> <!-- redo this in a bootstrappy way-->
<br>
<output id="output"></output>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="/js/jszip-load.js"></script>
<script src="/js/jszip.js"></script>
<script src="/js/jszip-inflate.js"></script>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
if (f.type !== "application/zip") {
document.getElementById('output').innerHTML = "<p class='text-error'>" + f.name + " isn't a zip file.</div>";
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var zip = new JSZip(e.target.result)
$.each(zip.files, function (index, zipEntry) {
if (zipEntry.name == "test.txt"){
var text = zipEntry.asText();
var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
for(var i = 0; i < lines.length; i++) {
if (lines[i].length > 240){
output.push('<li>' + lines[i] + '<br>');
}
}
document.getElementById('output').innerHTML = '<h2>Paths with more than 240 characters:</h2> <br><ol>' + output.join('') + '</ol>';
else{
alert("file not found!")
}
}
});
}
})(f);
}
}
document.getElementById('input').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
For some reason, I'm sure having to do with the way that I am using the closure, it is not actually parsing the .zip files in question. Any ideas what I might be doing wrong here?
I use this code and am able to get all file data. content variable has file content:
function loadSettingsFile(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
try {
var zip = new JSZip(e.target.result);
$.each(zip.files, function (index, zipEntry) {
var content = zipEntry.asText();
alert(content);
});
} catch(e) {
alert(e)
}
}
})(f);
// read the file !
// readAsArrayBuffer and readAsBinaryString both produce valid content for JSZip.
reader.readAsArrayBuffer(f);
// reader.readAsBinaryString(f);
}
}

Categories

Resources