I need to create extract the signature of a file at the client level itself so as to positively determine its file type. Below is my file input object:
<input id="test1" type="file">
I wrote the following javascript code against it:
var fileInput = document.getElementById('test1');
fileInput.addEventListener('change', function(e) {
console.log("file selected");
var reader = new FileReader();
reader.onload = function(e) {
console.log("loaded");
var file_slice = gcUploadFile.slice(0,4);
console.log(file_slice);
var arr_buffer = reader.readAsArrayBuffer(file_slice);
console.log(arr_buffer);
}
});
Check out the fiddle for the above.
The trouble I am having is that my code does not even enters the onload fucntion.
What am i doing wrong?
Note: I am coding only using plain javascript but i am open to use Google Closure.
Why would it reach the onload handler, nothing is ever read by the FileReader.
You have to pass the file to the fileReader by reading it as something
var fileInput = document.getElementById('test1');
fileInput.addEventListener('change', function(e) {
console.log("file selected");
var reader = new FileReader();
reader.onload = function(e) {
console.log("loaded");
var file_slice = gcUploadFile.slice(0,4);
console.log(file_slice);
var arr_buffer = reader.readAsArrayBuffer(file_slice);
console.log(arr_buffer);
}
reader.readAsBinaryString(e.target.files[0]);
});
Related
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');
..
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...
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.
I have a textarea that can, quite obviously, be edited using keyboard entry. I also want to be able to load a file using an html input. I have done so, using the onchange event. (jsfiddle code linked below).
Suppose I load a file using the file loader - which works correctly in the example.
Then, I edit this file. Realising that the changes I have made are not desired, I want to reload this file. However, when using the html input, nothing changes since the selected file remains the same (the onchange event is not triggered). Is there a way to reload a file using an html input. (The only workaround I have found is to load a different file, then reload the original file ... which is not very elegant).
http://jsfiddle.net/aroberge/8PZyK/1/
var load_file = function() {
$("#fileInput").show();
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$("#editor").text(reader.result);
$("#fileInput").hide();
};
reader.readAsText(file);
});
};
$("#load").on("click", function(evt) {
load_file();
});
You could clear out the fileInput value after you've read the file from it:
updated fiddle:
http://jsfiddle.net/8PZyK/8/
var load_file = function() {
$("#fileInput").show();
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
if (fileInput.files && fileInput.files.length > 0) {
var file = fileInput.files[0];
var reader = new FileReader();
fileInput.value = "";
reader.onload = function(e) {
$("#editor").val(reader.result);
$("#fileInput").hide();
}
};
reader.readAsText(file);
});
};
$("#load").on("click", function(evt) {
load_file();
});
After the file input has changed, and you grab out the data, simple reset the input field like so:
fileInput.value = ""; // Or with jQuery, $('input[file]').val('')
This will trigger another change (which you'll want to ignore), but will allow the user to select the same file again and still give you a change event.
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);