Referring to this thread:
Preview an image before it is uploaded
I would like to know how simply calling reader = new FileReader() lets FileReader know which file to read.
The thread link posted above works just fine for me, but when I try the following, FileReader() does not read the input. console.log returns nothing.
Javascript:
function fileReader(input){
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
};
}
$(function(){
$('#file').change(function(){
fileReader(this);
});
});
HTML:
<input id="file" type="file">
Why doesn't this work?
Is there a way to manually give FileReader() which input DOM to read?
I would like to know how simply calling reader = new FileReader() lets FileReader know which file to read.
It doesn't.
You missed this line from the answer of the question you linked to:
reader.readAsDataURL(input.files[0]);
Related
I have written the code below to display the text from a local file using the file API but when I click the button, nothing happens. I get the following error when I inspect the element in the browser. What am I doing wrong?
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<pre id="file"></pre>
<script>
document.getElementById("myBtn").addEventListener("click", function(){
var file = "test.txt"
var reader = new FileReader();
document.getElementById('file').innerText = reader.result;
reader.readAsText(file);
});
</script>
</body>
</html>
You've made a couple of errors.
The one that the error message is complaining about is that you are trying to select a file using a hard coded string. You cannot determine which file gets loaded. The File API will only allow you to read files that are selected by the user via a File input.
The second is that you are trying to read the result property of the reader before you've read the file. You need an event handler to do that (because file reading, like Ajax, is asynchronous).
document.getElementById("myBtn").addEventListener("click", function() {
var reader = new FileReader();
reader.addEventListener('load', function() {
document.getElementById('file').innerText = this.result;
});
reader.readAsText(document.querySelector('input').files[0]);
});
<input type="file">
<button id="myBtn">Try it</button>
<pre id="file"></pre>
To save the File content in innerHtml, you must first read the file. loadend event fires only when file is fully read, and you can access its content without errors:
var reader = new FileReader();
var fileToRead = document.querySelector('input').files[0];
// attach event, that will be fired, when read is end
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as a typed array
// we insert content of file in DOM here
document.getElementById('file').innerText = reader.result;
});
// start reading a loaded file
reader.readAsText(fileToRead);
You can read more here - and here
As the others said, I noticed that the onload event is what's missing.
So I have a couple of different ways of showing how to make the reader do something, one for doing the readAsText and one for getting the data as a base64 byte string using readAsDataURL, which is better, in my opinion, since you don't have to worry about Unicode and other weird question mark characters. To see them in action, just flip the call in the listener between uploadFile(); and uploadFile1();. And I show a couple of different ways you can grab the file object, as well:
document.getElementById("myBtn").addEventListener("click", function() {
uploadFile1();
});
function uploadFile1(){
var f = myInput.files[0];
var reader = new FileReader();
reader.onload = processFile(f);
reader.readAsText(f);
}
function uploadFile(){
var f = document.querySelector('input').files[0];
var reader = new FileReader();
reader.onload = processFile(f);
reader.readAsDataURL(f);
}
function processFile(theFile){
return function(e) {
// Use the .split I've included when calling this from uploadFile()
var theBytes = e.target.result; //.split('base64,')[1];
document.getElementById('file').innerText = theBytes;
}
}
<input id="myInput" type="file">
<button id="myBtn">Try it</button>
<span id="file"></span>
And normally I would think you should be able to just do:
<input type="button" onclick="uploadFile()" id="myBtn">Try it</button>
instead of having to add that listener, but it wasn't working in JSFiddle for some reason.
https://jsfiddle.net/navyjax2/heLmxegn/1/
Well! not sure about the others, but in my case it was solved by using fileObjects[0].file
A good way to look at it would be to print your 'files' or 'fileObjects' in the console and then see whether you require the .file in the end.
Newbie to the HTML5 file upload capability, and finding I cant get a simple xml file uploaded and able to get file contents into console. The expected behaviour is that I'd select an xml file and then see the contents rendered in console. However, I dont ever get to the console.log step - seems the reader never loads? Any suggestions to resolve would be most appreciated.
<input type="file"></input>
<script>
var upload = document.getElementsByTagName('input')[0];
upload.onchange = function (e) {
e.preventDefault();
var file = upload.files[0], reader = new FileReader();
reader.onload = function (event) {
console.log('evt',reader.readAsText(file));
};
return false;
};
</script>
So you're setting the reader.onload event to a function, but you need to call the reader.readAsText() function outside of this.
So for example change your code to:
reader.onload = function(event) {
console.log(event);
};
reader.readAsText(file);
What this does is to tell the reader that when you call reader.readAsText(file) it should run the function you defined with reader.onload.
What you were doing before would never load the file because you were only telling the reader to readAsText inside your function callback that you told it to run when it was already loaded!
I have a page use fileReader to preview the upload image.
I have test in my local machine, it works fine, but when I test in JS fiddle, it is not working. anyone know where is the problem?
if(window.FileReader){
function preview(input){
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function(e){$('#previewImage').attr('src', e.target.result);}
}
}
}else{alert("file reader not support");}
here is fiddle http://jsfiddle.net/s39P3/93/
If you have the console open you will see the error is that the 'preview' function isn't found, because it isn't part of the scope. I added it to the window scope so window.preview = function() and now it works.
http://jsfiddle.net/s39P3/93/
I've got a drag and drop script that uses readAsArrayBuffer(). The length of the buffer is perfect, but I can't seem to figure out how to pull the data out of the buffer.
Apparently I've got to make a DataView or an Uint8Array or something, then iterate through its byteLength...help!
EDIT
Pertinent code (there's not much of it):
var reader = new FileReader();
reader.onload = function(e) {
// do something with e.target.result, which is an ArrayBuffer
}
reader.readAsArrayBuffer(someFileHandle);
This might change based on your answer to my comment, but if I assume that you are using a FileReader somewhere, you need to read it's result attribute in the loaded callback that you need to provide:
function loaded(evt) {
var datastring = evt.target.result;
// do something here
}
reader.onload = loaded; // where reader is a FileReader, FileReaderSync
Update: Ah, I see. Well then your best course of action is to follow to this duplicate:
Converting between strings and ArrayBuffers
Update2: Note that you could probably use readAsText() then, but I don't know if you're at liberty to do this.
I am using below code to read a ZIP file at client side
var Zfile = new Zipfile( $('#xfilex').val() );
var file = Zfile.entries[0];
// From Here file reading continues... I am giving this to say what I am trying to accomplish
if(file)
{
var reader;
reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = loaded;
}
But I am unable to read the file... Please help me to find mistakes in the above code. It is pure JavaScript and taken the reference from Unzipping files Question. I hope I can get help.