Reading a file in chrome - javascript

I am trying to write a java script to read a file in chrome and I am using the javascript debugger of chrome.
here is the script:
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result;
};
console.log("File contents: " + contents);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
when i run the code the contents variable is undefined. Plenty of discussion has gone into this but i have not found a solution. I am using the --allow-file-acess-from-files option.
Now the following code works in a strange manner:
<script>
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result ;
};
console.log(e.target.result);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
It throws an error which is "Uncaught TypeError: Cannot read property 'target' of undefined"
However in the watch expression window the following variables show that the file is being read.
event.target.result: "firmware file
↵:10000000782600204D4B0000B94B0000B94B000092
↵:10001000B94B0000B94B0000B94B000000000000D4
↵:10002000000000000000000000000000B94B0000CC
↵:10003000B94B000000000000B94B0000210B00008C
↵:10004000B94B0000B94B0000B94B0000B94B0000A0
↵:10005000B94B0000B94B0000B94B0000B94B000090
↵:10006000B94B0000B94B0000B94B0000B94B000080
↵:10007000B94B0000B94B0000B94B0000B94B000070
↵:10008000B94B0000B94B0000B94B0000B94B000060
and the same ouput for e.target.result and contents variable.
Why is the code behaviour is so wierd?
Kindly help me out. I am not very skilled with javascripting.

e.target will be undefined on your 2nd console.log there towards the bottom - only one is inside your onload function, and therefore has e set.
The second one is acting on the var e ; you defined at the top, which is null, and therefore e.target.result is invalid.
e: in other words, delete this line, or move it into the function:

Related

Javascript inline script onchange not working

i'm having a problem on making my code to adjust to my web server, because of the security purposes, all inline javascript code to my html is not allowed.
everything is already okay i'm just having a hard time converting my other code to pure javascript
Here is my existing code,,,
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment id="openQRCamera" tabindex=-1></label>
the original code is this
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment onchange="openQRCamera(this);" tabindex=-1></label>
the onchange is not working because it is inline in the html.
this function needs to open a camera and detect if there is a qr that exists.
here is what i have now on converting it.
document.querySelector("#openQRCamera").addEventListener('onchange', (node) => {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
});
here is the original code
function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}
i am using this website as my source of code, everything is working fine in my localhost, but the server is just strict, and i think that's normal for all the websites.
https://www.sitepoint.com/create-qr-code-reader-mobile-website/
i just been stuck and try to do other solution like adding event listener, and append of input just by using jquery, but it's not working. thanks in advance.
The event listener you are using is faulty, instead of listenning to 'onchange' you have to listen to 'change' like so:
document.querySelector("#openQRCamera").addEventListener('change', () => {
//remove the node as parameter and get it with javascript:
var node = document.getElementById('openQRCamera');
..

FileReader doesnot work without choosing a file

I have used FileReader to read the selected file using javascript. Here is the code
HTML:
<img id="preview" ng-src="{{user_picture}}" ng-click="triggerUpload()" alt="" width="160" height="160" class="img-thumbnail" />
<input type="file" onchange="angular.element(this).scope().viewImage(this.files)" accept="image/jpg,image/jpeg,image/png" id="fileInput" name="filedata" />
SCRIPT:
$scope.triggerUpload = function () {
show_image();
}
$scope.list = [];
$scope.viewImage = function (file) {
show_image(file);
}
function show_image(image) {
var fileuploader = angular.element("#fileInput");
fileuploader.on('click', function () {
if (image && image[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
})
fileuploader.trigger('click');
}
This works fine when I select an file from the upload dialog box. But, when I click 'Cancel' or exit the uploader without selecting any file, I get the error below.
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader':
parameter 1 is not of type 'Blob'.
How to solve this problem??
How to solve this problem??
Don't call show_image when user selects cancel
function show_image(image) {
if (image && image[0] && this.files.length) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
}
The condition above checks for image && image[0] which (if our guess is correct without more code to explain it) check for this variable to be non-null.
However you are calling readAsDataURL() on this.files[0]; this variable has nothing to do with image, and most likely you are not setting it or it is not a filename when the user has pressed cancel.
Without more code, we cannot guess a more accurate answer...

Uncaught TypeError: Cannot read property 'addEventListener' of null error for image upload

Hi friends i am getting this error in following code:
Uncaught TypeError: Cannot read property 'addEventListener' of null on line 11
The line 11 is:
fileDiv.addEventListener("click",function(e){
$(fileInput).show().focus().click().hide();
e.preventDefault();
},false)
This is input file:
<input type="file" class="imageUploadBtn" id="upload-image" name="fotograflar[]" multiple="multiple">
In this code error on line 5:
console.log(fileInput);
fileInput.addEventListener("change",function(e){
var files = this.files
showThumbnail(files)
},false)
What is that error? Anyone can help me in this regard ? I am using this code for image upload but this error will not allow me!!
$(document).ready(function()
{
jQuery(function($){
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-image");
console.log(fileInput);
fileInput.addEventListener("change",function(e){
var files = this.files
showThumbnail(files)
},false)
fileDiv.addEventListener("click",function(e){
$(fileInput).show().focus().click().hide();
e.preventDefault();
},false)
fileDiv.addEventListener("dragenter",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("dragover",function(e){
e.stopPropagation();
e.preventDefault();
},false);
fileDiv.addEventListener("drop",function(e){
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
showThumbnail(files)
},false);
function showThumbnail(files){
for(var i=0;i<files.length;i++){
var file = files[i]
var imageType = /image.*/
if(!file.type.match(imageType)){
console.log("Not an Image");
continue;
}
var image = document.createElement("img");
// image.classList.add("")
var thumbnail = document.getElementById("thumbnail");
image.file = file;
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function(aImg){
return function(e){
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload= function(){
ctx.drawImage(image,100,100)
}
}
}
});
});
Your code is looking for and element with ID 'upload':
'var fileDiv = document.getElementById("upload");'
but the actual id is 'upload-image'
<input type="file" class="imageUploadBtn" id="upload-image" name="fotograflar[]" multiple="multiple">
Change your this line to:
var fileDiv = document.getElementById("upload-image");
If it is working on localhost, then try this:
1. open your page in chrome browser
2. hit F12
3. on console of developer tool, type document.getElementById("upload");
4. Whatever is the output just move your mouse cursor on that to see where is that element on UI
5. Repeat same with non localhost environment and verify/debug where is the problem.
This is to simple a problem and I am sure if you fiddle with debugger you can solve it yourself easily.
We should also check where are we calling the javascript file in header or in the end of the <body>
getElementById returns null when it can't find the element you're looking for. Trying to call functions on null will throw an error like the above. It seems just from the above that you do not have element with the ID upload.

FileReader isn't working?

this is frustrating. I've been running this code in Safari, Firefox and Chrome - all latest versions - and it doesn't work. Is it working for anyone else? I'm getting my file reference from <input type='file' id='file' name='file'>
console.log("Have now created a new file reader and it looks like this..." + reader);
reader.onload = function() {
var contents = event.target.result;
console.log("File contents: " + contents );
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
}, false);
What am i doing wrong?
Thanks,
J.Wells
What am i doing wrong?
You seem to have forgotten the event parameter of the onload handler. Instead of using event.target, you also might just use reader.
Also, in the fiddle you are creating the FileReader in a very odd way. You might want to read the introduction Using files from web applications at MDN.
document.getElementById("file").addEventListener("change", function(e) {
var file = e.target.files[0],
reader = new FileReader();
console.log("Have now created a new file reader and it looks like this..." + reader);
reader.onload = function(event) {
// ^^^^^
var contents = event.target.result;
console.log("File contents: " + contents );
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file);
}, false);

function will not call another function, javascript

For a class project i am trying to count the number of clicks a button gets, save the search term, and then open a new html file. my problem is that the "doCoolThings" function will not call the "newWindow" function. I cannot figure out how to get the newWindow function to execute after i click submit.
here is my code:
window.onload = init;
function init() {
var myButton = document.getElementById("submitButton");
myButton.onclick = doCoolThings;
}
function doCoolThings(){
alert("test count");
localStorage.searchTerms = document.getElementById("searchWord").value;
//var searchOutput = document.getElementById("searchOutput");
searchWord.innerHTML = searchTerms;
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
//window.open("scroogleresults.html");
}
else
{
localStorage.clickcount=1;
//window.location="scroogleresults.html";
}
var myCounter = document.getElementById("numberClicks");
var counter = localStorage.clickcount;
myCounter.innerHTML = counter;
newWindow();
}
function newWindow(){
alert("new window");
window.open("scroogleresults.html");
}
If this is the extent of your code, it looks to me like you have some javascript errors. You should be checking the error console or debug console in your browser for javascript errors that cause your scripts to abort. Here are a couple errors I see:
Error #1
In doCoolThings(), when you do this:
searchWord.innerHTML = searchTerms;
I don't see any place that searchTerms is defined so this would generate a script error.
Error #2
You should be using getItem() and setItem() to access localStorage.

Categories