parameter is not of type 'Blob' - javascript

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.

Related

HTML5 Filereader always returns empty string?

I'm just learning how to use the filereader now, and I duplicated an example I found online to experiment with, but for some reason, the filereader always returns an empty string.
First, I have an HTML form for the user to select a file, which then calls the script:
<input type="file" id="filelist" onchange="selectfile()">
Here's the script:
function selectfile() {
myFile = document.getElementById("filelist").files[0];
reader = new FileReader();
reader.readAsText(myFile);
myResult = reader.result;
alert(myFile.name);
alert(myResult);
alert(reader.error);
}
I have tried this with a number of different text files I typed up in Notepad, and in every case the results are the same. I'm only ever submitting one file through the html form.
The 3 alerts are for testing.
It displays the file name correctly.
It displays an empty string for the result.
It displays NULL for the error so it's not getting an error.
I searched around to see if there was something obvious here already, but couldn't find anything that seemed to point me in the right direction.
Thoughts?
The FileReader object is not ready yet. You need to add an onload event listener to the reader and then make a call to the readAsText method. You can then access the file contents from inside the callback function.
MDN docs - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result
function selectfile() {
myFile = document.getElementById("filelist").files[0];
reader = new FileReader();
reader.onload = () => {
myResult = reader.result;
alert(myFile.name);
alert(myResult);
alert(reader.error);
};
reader.readAsText(myFile); // only accessible when the FileReader is loaded
}
<input type="file" id="filelist" onchange="selectfile()">

Printing File Contents after HTML button is pressed

I am trying to read a users local file after a button is pressed. Right now, the code looks like this:
HTML:
<label for="evidence_file">Please choose a file to upload for evidence:</label><br><input type="file" id="fileElem"><br>
<button type="button" id="Submit">Submit Evidence </button>
JAVASCRIPT:
document.getElementById("Submit").onclick = function () {
file = document.getElementById("fileElem").files[0];
const fr = new FileReader();
fr.onload = function(file) {
console.log(file);
};
fr.readAsTest(file);
}
However, the file reader "onload" function is never running. By this, I mean that the function is never triggered (and the console never prints file). Is there a reason for this? Thanks.
In your code example you call readAsTest which is a typo for readAsText. If that's a copy and paste mistake and your code works, try adding an error handler to the file reader and see if it gives you something to go on.

in js, why is my filereader unable to track my inputfile when I edited it

Maybe naive question but I'm wondering this:
I have an html input allowing me to find a local file on my computer. <input type="file" id="importFile">
From this input, i create a FileReader in js to display the text file content on my page
var search_file = document.getElementById("search_file")
search_file.addEventListener('change', function(){
var reader = new FileReader();
var tmp = [];
reader.readAsText(file_to_survey);
reader.onload = function(e) {
var contents = e.target.result;
//function to edit html thanks to content//
}, false);
This part is actually working well BUT if I edit or replace the file I targeted (with exact same file name), I'm not able to display the file without to search it again with the html input mentionned above.
Is there a way to keep trace of my file even after edition?
Many thanks for your help. I dug quiet a lot to solve my problem but maybe I'm thinking the wrong way. Any clue would be nice.
Because that's how the input type=file element works, and to my best knowledge there is no way for you to force the browser to automatically re-read a file from the user's hard drive without their express consent.
You can put the change handler of the file input in a separate function, and call that function when needed.
function loadFile () {
var reader = new FileReader();
reader.addEventListener('load', function () {
file = reader.result;
// Handle the changes here
console.log(file);
});
reader.readAsText(fileField.files[0]);
}
const fileField = document.getElementById('load'),
reloadBut = document.getElementById('reload');
let file;
reloadBut.addEventListener('click', loadFile);
fileField.addEventListener('change', loadFile);
<input type="file" id="load">
<button id="reload">Load</button>
A separate button is used to reload the file in this snippet, but you can call loadFile where ever you need, ex. in an interval or from some event handler knowing the file was changed etc.
Note: This works in Chrome only, other browsers seem to lose the reference to the file browsed into file input when the file is changed. Also, the file must be properly closed after saving, before reloading.

Using only pure javascript how to get file name, format and content of a browsed file

I need to get the name, format and content of a browsed file only, multiple files not required. Even I cant use any HTML5 API/jQuery. Could you please guide me, using only pure JavaScript how do I solve this.
Here is the fiddle:
[https://jsfiddle.net/summtz8m/][1]
After getting all I need to click ImportASN1 button to POST data in REST service.
Here is my HTML
<button class="ebBtn" id="importButt" name="importButt"><span>Import ASN1</span></button><input type="file" id="myfile" name="myfile"><p id="contents"></p>
Here is my JS
var file = document.getElemtById("myfile").files[0];
console.log(file);
if (file) {
// create reader
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
// browser completed reading file - display it
console.log(e.target.result);
};
}
Your current code runs on page load. But at that time the file input is not filled out yet! Instead, listen to the click event on the button, or the change event on the file input.
In addition, there is a typo: document.getElemtById should be document.getElementById. Use the developer console in your browser (F12 → Console in many browsers) to find these errors.
The file name will then be present in the file.name property.
<script>
document.getElementById("myfile").addEventListener('change', function(ev) {
var file = ev.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(e) {
console.log(file.name, e.target.result);
};
});
</script>

Loading and Reading text file onto HTML/JavaScript

I am trying to read and load a locally stored text file (it's saved on the user's computer, but may be moved to a local directory) into a variable or array so that I can generate a table with it in HTML.
I have found a way to have the user select and upload the file, but the code displays the text on the browser. I want it stored so I can manipulate the data so that I can put it in the correct row and cell. I know how to create a table, format it, format and splice text and things similar to that.
The code, which I found here but forgot which specific ask it was, goes as follows
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
For reference, here's a sample of the text file and here's what I want.
I am still relatively new to HTML and Javascript, but eager to learn. Anything will be appreciated.
You already have some parts working:
You have found a way to have the user select and upload the file
You know how to create a table, format it, format and splice text and things
Now we need to connect these things. Unfortunately, now all the script does is display the text on the browser when the user loads a text file. This is the part of the code responsible for that:
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
It displays it inside the <pre id="fileDisplayArea"><pre> area of your html. You want to store it inside a variable, so you can start to create a table, format it, format and splice text and things (the part 2 you already know):
reader.onload = function(e) {
myTextToFormat = reader.result;
// start formatting and make it into a table...
}

Categories